在C ++中定义对象而不调用其构造函数 [英] Defining an object without calling its constructor in C++
本文介绍了在C ++中定义对象而不调用其构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C ++中,我想将一个对象定义为此类的成员:
In C++, I want to define an object as a member of a class like this:
Object myObject;
但是这样做会尝试调用它的无参数构造函数,该构造函数不存在。但是,我需要在包含类完成一些初始化之后调用构造函数。
However doing this will try to call it's parameterless constructor, which doesn't exist. However I need the constructor to be called after the containing class has done some initialising. Something like this.
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
Store a pointer to an Object
rather than an actual 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
}
}
不要忘记在析构函数中删除
。现代C ++可以为您提供帮助,因为您可以使用 auto_ptr shared_ptr而不是原始内存指针。
Don't forget to delete
it in the destructor. Modern C++ helps you there, in that you could use an auto_ptr shared_ptr rather than a raw memory pointer.
这篇关于在C ++中定义对象而不调用其构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文