我在类中使用结构变量,我想在类构造函数中分配该变量的参数值。
但是我找不到编译的方法。你能告诉我怎么做吗?这是我的代码示例
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 }
{}
};
或 Aggregate Initialization 自
mystruct
是一种聚合类型,您可以执行 aggregate initialization也。这将是您的案例所需的最小更改,并且不需要 mystruct
中的构造函数.class myclass
{
mystruct s_;
public:
myclass(int n)
: s_{ n } // aggregate initialization
{}
};
关于c++ - 在类构造函数中定义结构变量的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62622535/