假設我有一個類A,它使用網路訊息。類A有 2 個成員,b并且c具有相應的型別B和C。成員只能使用來自網路的資訊進行初始化。
有沒有辦法在稍后初始化成員,而不必讓成員屬于B*and C*(用 nullptr 初始化并稍后設定所需的值)?
我覺得在這種情況下設計有缺陷,但我仍在問自己最佳實踐是什么,因為我在閱讀后使用指標時有點遲鈍為什么我應該使用指標而不是物件本身??
uj5u.com熱心網友回復:
std::optional<T>是圍繞 type 的“可空”包裝器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。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368067.html
