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

标签 c++ class c++11 parameters constructor

我在类中使用结构变量,我想在类构造函数中分配该变量的参数值。
但是我找不到编译的方法。你能告诉我怎么做吗?这是我的代码示例

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/

相关文章:

c++ - 重载赋值运算符还是使用默认运算符?

C++:从键和值 vector 插入 boost::unordered_map

c++ - 尝试使用分配器构造 std::list 时失败

python 类就像一个列表

c++ - 我的 SFINAE 检查 std::map/std::vector 有什么问题?

C++ 如何在静态库的命名空间中设置私有(private)类成员?

c++ - : expected constructor, 析构函数错误,或者 ‘::’ token 之前的类型转换

c++ - 多线程程序挂起条件等待

c++ - 我什么时候应该使用新的 ranged-for,我可以将它与新的 cbegin/cend 结合使用吗?

c++ - 带有可变参数的模板函数编译问题