gpt4 book ai didi

c++ - 在 C++ 中定义对象而不调用其构造函数

转载 作者:IT老高 更新时间:2023-10-28 14:00:29 26 4
gpt4 key购买 nike

在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com