在 C++ 中,我想将一个对象定义为这样的类的成员:
Object myObject;
但是这样做会尝试调用它的无参数构造函数,它不存在。但是,我需要在包含类完成一些初始化之后调用构造函数。像这样的。
class Program
{
public:
Object myObject; //Should not try to call the constructor or do any initializing
Program()
{
...
//Now call the constructor
myObject = Object(...);
}
}
最佳答案
存储指向 Object
的指针,而不是实际的 Object
因此:
class Program
{
public:
Object* myObject; // Will not try to call the constructor or do any initializing
Program()
{
//Do initialization
myObject = new Object(...); // Initialised now
}
}
别忘了在析构函数中delete
它。现代 C++ 可以帮助您,因为您可以使用 auto_ptr shared_ptr 而不是原始内存指针。
关于c++ - 在 C++ 中定义对象而不调用其构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7557153/