【问题标题】:error: no matching function call when adding parameters to class constructor错误:向类构造函数添加参数时没有匹配的函数调用
【发布时间】:2021-01-23 01:07:11
【问题描述】:

我有一个类“a”,它有一个类“b”的实例。以下代码在问题标题中给出了错误,但是当我将 b 更改为不带任何参数时,代码运行时没有错误。

class b
{
public:
    b(int);
};

class a
{
  public:
  b bObj;
      a(int arg1, const std::string& arg2);
};

a::a(int arg1, const std::string& arg2){
  bObj = b(5);
}

b::b(int IDD2){
  srand(time(0)+IDD2);
}

在“b”没有参数的情况下运行此代码有效,但我实际上需要传入一个值。为什么会出现这个错误?

【问题讨论】:

    标签: c++ parameters arguments


    【解决方案1】:

    a的构造函数中,必须先构造bObj才能进入函数体。但是b 没有零参数构造函数,并且您没有提供默认初始化程序,因此会出错。

    相反,您可以使用成员初始化器列表在到达构造函数主体之前初始化bObj

    a::a(int arg1, const std::string& arg2) : bObj(5) {}
    

    或者在类中提供默认值:

    class a
    {
      public:
      b bObj = 5;
      a(int arg1, const std::string& arg2);
    };
    

    【讨论】:

    • 我明白了。第二种情况的语法对我来说很奇怪。如果有多个整数参数怎么办。我会使用以下内容吗? b bObj = 5, 2;
    • @MrMultiMediator 你可以做b bObj{5, 2};
    猜你喜欢
    • 2020-06-09
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多