Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在类构造函数中定义结构变量的参数_C++_Class_C++11_Parameters_Constructor - Fatal编程技术网

C++ 在类构造函数中定义结构变量的参数

C++ 在类构造函数中定义结构变量的参数,c++,class,c++11,parameters,constructor,C++,Class,C++11,Parameters,Constructor,我在类中使用一个struct变量,我想在类构造函数中指定该变量的参数值 但我找不到编译的方法。你能告诉我怎么做吗?这是我的代码示例 struct mystruct { int myvar; } class myclass { mystruct s_; public: myclass(int n) : s_.myvar{ n } {} }; 您的mystruct需要一个合适的构造函数,它将intger作为参数 struct mystruct { int myvar;

我在类中使用一个struct变量,我想在类构造函数中指定该变量的参数值

但我找不到编译的方法。你能告诉我怎么做吗?这是我的代码示例

struct mystruct
{
   int myvar;
}

class myclass
{
   mystruct s_;

public:
   myclass(int n) : s_.myvar{ n } {}
};

您的
mystruct
需要一个合适的构造函数,它将
int
ger作为参数

struct mystruct
{
   int myvar;
   mystruct(int val)  // provide this constructor and good to go!
      : myvar{ val }
   {}
};

因为
mystruct
是一种聚合类型,所以您也可以这样做。这将是您的案例所需的最小更改,并且不需要
mystruct
中的构造函数

class myclass
{
   mystruct s_;
public:
   myclass(int n)
      : s_{ n } // aggregate initialization
   {}
};

您可以在构造函数中初始化s_wk.myvar,如下所示:

Myclass(int n) {
    s_.myvar = n;
}

myclass(int n){s_{.myvar=n;}
myclass(int n):s_{n}{}或自C++20以来,使用指示符的更清晰的聚合初始化版本:
myclass(int n):s_{.myvar=n}