当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - How to pass a pointer to a constructor?

问题描述:

I understand how to create an object and i understand how to then create a pointer to that object.

But I'm struggling to create a pointer to an object within another object/class.

I have created a Car and an Engine class.

I want to have the Car class to have a pointer to an engine object that will be passed into the Car class's constructor. I am having no luck trying to figure out the correct syntax to do this.

Engine.h

#pragma once

class Engine

{

private:

int _power;

public:

Engine(int);

~Engine();

int getPower();

void setPower(int);

};

Engine.cpp

#include "stdafx.h"

#include "Engine.h"

Engine::Engine(int power)

{

_power = power;

}

Engine::~Engine()

{

}

int Engine::getPower()

{

return _power;

}

void Engine::setPower(int power)

{

_power = power;

}

Car.h

#pragma once

#include "Engine.h"

class Car

{

private:

Engine* _engine;

public:

Car();

~Car();

};

Car.cpp

#include "stdafx.h"

#include "Car.h"

Car::Car(Engine &engine)

{

_engine = engine;

}

Car::~Car()

{

}

Could someone please show me how I would go about this?

网友答案:

Simply change in Car.cpp

Car::Car(Engine &engine){...}

to

Car::Car(Engine* engine): _engine(engine){}

and also don't forget to change the signature of the constructor in Car.h to

Car(Engine*);

Otherwise you are mixing pointers with references, which are not semantically the same. Also consider using constructor initializer lists instead of assignments inside the constructor. For PODs it makes no difference, but for expensive-to-construct objects it makes a difference, since first the object is default-constructed, then assigned to it via a copy constructor.

分享给朋友:
您可能感兴趣的文章:
随机阅读: