【问题标题】:Defining a parameter of a struct variable in a class constructor在类构造函数中定义结构变量的参数
【发布时间】:2020-10-18 16:42:16
【问题描述】:

我在类中使用结构变量,我想在类构造函数中分配该变量的参数值。

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

struct mystruct
{
   int myvar;
}

class myclass
{
   mystruct s_;

public:
   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 } {}

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


【解决方案1】:

为此,您的mystruct 需要一个合适的构造函数,该构造函数将intger 作为参数。

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
   {}
};

【讨论】:

    【解决方案2】:

    您可以像这样在构造函数中初始化 s_.myvar:

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

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2017-10-02
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 2012-01-20
      • 2021-07-06
      • 2021-12-24
      • 2011-10-31
      相关资源
      最近更新 更多