【问题标题】:Initialize members at later point without using pointers possible? C++稍后在不使用指针的情况下初始化成员? C++
【发布时间】:2021-12-24 01:09:58
【问题描述】:

假设我有一个类A,它使用网络的消息。 A 类有 2 个成员 bc,对应类型为 BC。成员只能使用来自网络的信息进行初始化。

有没有办法在稍后初始化成员,而无需将成员的类型设为 B*C*(使用 nullptr 初始化并稍后设置所需的值)?

我觉得在这种情况下设计有缺陷,但我仍然在问自己最好的做法是什么,因为我在阅读 Why should I use a pointer rather than the object itself? 后使用指针时有点迟钝?

【问题讨论】:

  • std::optional<B>std::optional<C> 怎么样?
  • @FrançoisAndrieux 我是一个初学者,我不熟悉 c++ 提供的所有功能。我得查一下,但这可能正是我所要求的。
  • 如果不设置会有什么问题?
  • @АлексейНеудачин 例如当 b 和 c 没有默认构造函数时
  • 所以你做不到

标签: c++ c++11 c++17


【解决方案1】:

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,如果那里什么都没有。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2010-10-16
    相关资源
    最近更新 更多