gpt4 book ai didi

c++ - 如何初始化用户定义数据类型的 std::optional

转载 作者:行者123 更新时间:2023-11-27 23:56:05 24 4
gpt4 key购买 nike

我正在尝试学习 C++ 17 的新特性。

请找到下面的代码:

class Test
{
public:
Test(int x):y(x){}
~Test(){}
int getx()
{
return x;
}
private:
int x;
};
struct Container
{
std::optional<Test> test;
};
int main()
{
struct Container obj;
// here i want to initialize the member "test" of
// struct Container
obj.test = make_optional<Test>(10); ----> is this correct??
}

有人可以告诉我如何初始化 std::optional 吗?例如,如果我这样声明:

std::optional<Test> t

如何初始化它?

最佳答案

obj.test = make_optional<Test>(10);

----> is this correct??

是的。你也可以这样做:

obj.test = Test(10);

关于c++ - 如何初始化用户定义数据类型的 std::optional,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42537687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com