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

标签 c++ c++17

我正在尝试学习 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/

相关文章:

c++ - 将 std::string_view 与需要以空字符结尾的字符串的 api 一起使用

c++ - 应该在带花括号的 return 语句中调用什么构造函数?

c++ - 从 C++ 中的类型列表获取类型索引

c++ - 有什么方法可以在 C++ 中分解出 "const"字段初始值设定项

C++ MFC 按钮在窗口调整大小时消失

c++迭代具有可变方向的 vector

c++ - 使用 LAPACK 访问子矩阵

c++ - 头文件中的函数

c++ - 为什么 AddressSanitizer 报告范围后堆栈使用错误?

c++ - 可变函数和折叠表达式 : Fatal Error while trying to compile in Visual Studio 2017