我来自Java背景。我有以下程序。
#include <string>
#include <iostream>
class First {
public:
First(int someVal): a(someVal) {
}
int a;
};
class Second {
public:
First first;
Second() { // The other option would be to add default value as ": first(0)"
first = First(123);
}
};
int main()
{
Second second;
std::cout << "hello" << second.first.a << std::endl;
}
在 Second
类中,我希望变量 first
保持未初始化状态,直到我在 Second()
构造函数中明确初始化它。有没有办法做到这一点?或者我只能选择以下两个选项:
- 提供一个无参构造函数。
- 用某个默认值初始化它,然后重新分配所需的值。
我不能在初始化列表中使用正确的值初始化 first
,因为该值是在一些操作之后获得的。因此,first
的实际所需值仅在 Second()
构造函数中可用。
Second
,first
就会被初始化。这是无法避免的。你只能在以后的阶段改变它的值。 - juanchopanzaSecond() : first(0) { first = First(123); }
- linuxeasyfirst
的初始化来实现。使用一个函数。 - Mooing Duckunique_ptr
或shared_ptr
,具体取决于需要做什么样的析构函数、赋值和复制操作。 - Phil Miller