C++ 在类构造函数中定义结构变量的参数
我在类中使用一个struct变量,我想在类构造函数中指定该变量的参数值 但我找不到编译的方法。你能告诉我怎么做吗?这是我的代码示例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 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}