我来自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()'s constructor
中专门对其进行了初始化。有办法吗?还是我只剩下两个选择?:
我无法使用正确的值初始化初始化列表中的first
,因为该值是在某些操作后获得的。因此,first
的实际所需值仅在Second()
构造函数中可用。
first
。first
用作指针,并在需要时随时对其进行初始化: