我有 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()
仅构造函数。
我的建议:使用一个函数:
private: static int calculate_first(int input) {return input*5;}
explicit Second(int input) : first(calculate_first(input)) {}
基类将按照它们在类继承列表中声明的顺序进行初始化,然后成员将按照它们在类中列出的顺序进行初始化,因此计算can依赖于非静态成员变量和基类if它们已经被初始化了。
Alternatively:
默认构造函数,然后重新分配:
explicit Second(int input) { first = input*5; }
虚拟值,然后重新分配:
explicit Second(int input) : first(0) { first = input*5; }
使用 boost::可选 (或标准::可选 https://en.cppreference.com/w/cpp/utility/optional从 C++17 开始):
boost::optional<First> first;
explicit Second(int input) { first = input*5; }
使用堆:
std::unique_ptr<First> first;
explicit Second(int input) { first.reset(new First(input*5));}
Second(const Second& r) first(new First(*(r->first))) {}
Second& operator=(const Second& r) {first.reset(new First(*(r->first)));}
安置新:
This is tricky and not suggested
and worse in every way than boost::optional
So sample deliberately missing.
But it is an option.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)