我有一个类,构造函数接受一个参数。例如,
class Entity
{
private:
int number_;
public:
Entity(int number):number_(number)
{
std::cout << "Entity object created";
}
}
// header
class SuperEntity
{
private:
Entity *entity_;
public:
SuperEntity(int value);
};
// source
SuperEntity::SuperEntity(int value)
{
entity_ = new Entity(value);
}
类 SuperEntity
有一个私有(private)成员 Entity
。因为为了实例化 Entity
您需要将 int
传递给它的构造函数并且不能完成声明文件 (superentity.h
) 因为实例化Entity
所需的int
值尚不可用,是否可以在SuperEntity
中动态分配Entity
'构造函数?这是一种不好的做法吗?谢谢。
最佳答案
正如 Dietmar 所说,使用成员初始化列表:
class SuperEntity
{
Entity entity_;
public:
SuperEntity( int value )
: entity_{ value }
{}
};
关于c++ - 是否因为以下原因在堆中实例化一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48046857/