稍后初始化成员而不使用指针可能吗? C++
Initialize members at later point without using pointers possible? C++
假设我有一个 class A
,它使用网络消息。 Class A
有 2 个成员 b
和 c
对应类型 B
和 C
。成员只能用来自网络的信息初始化。
有没有办法在以后初始化成员,而不需要成员是 B*
和 C*
类型(使用 nullptr 初始化并稍后设置所需的值)?
我觉得在这种情况下设计有缺陷,但我仍然在问自己最好的做法是什么,因为我在阅读后使用指针时有点迟钝 Why should I use a pointer rather than the object itself? ?
std::optional<T>
是类型 T
的“可空”包装器。它在语法上有点像指针,但没有动态分配。
std::optional<int> bob;
if (bob) // is there anything in the box?
std::cout << *bob; // print what is in the box.
你可以这样做:
bob = 7; // Assign 7 to what is in `bob`, or construct with a 7.
bob.emplace(3); // construct the contents of `bob` with the value 3
阅读时,您可以:
std::cout << bob.value_or(-1);
打印 bob
中的值,或者(T
构造自)-1
如果那里什么都没有。
假设我有一个 class A
,它使用网络消息。 Class A
有 2 个成员 b
和 c
对应类型 B
和 C
。成员只能用来自网络的信息初始化。
有没有办法在以后初始化成员,而不需要成员是 B*
和 C*
类型(使用 nullptr 初始化并稍后设置所需的值)?
我觉得在这种情况下设计有缺陷,但我仍然在问自己最好的做法是什么,因为我在阅读后使用指针时有点迟钝 Why should I use a pointer rather than the object itself? ?
std::optional<T>
是类型 T
的“可空”包装器。它在语法上有点像指针,但没有动态分配。
std::optional<int> bob;
if (bob) // is there anything in the box?
std::cout << *bob; // print what is in the box.
你可以这样做:
bob = 7; // Assign 7 to what is in `bob`, or construct with a 7.
bob.emplace(3); // construct the contents of `bob` with the value 3
阅读时,您可以:
std::cout << bob.value_or(-1);
打印 bob
中的值,或者(T
构造自)-1
如果那里什么都没有。