找不到默认的构造函数 [英] No default constructor found

查看:54
本文介绍了找不到默认的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想使用默认的构造函数,所以我实现了我的

I don't want to use the default constructor so I implement mine

class A
{
  public:
     A(int&i);
     A& operator=(const A& a);
     A(const A&a);
};

但是在B类中

class B
{
   A a;
   public:
     B(const A&a){this->a=a;}
}

然后出现错误:

找不到合适的A的默认构造函数.

no appropriate default constructor of A found.

推荐答案

使用构造函数初始化列表,因此成员 a 通过复制构造函数进行初始化:

Use a constructor initialization list, so the member a is initialized via the copy constructor:

B(const A&a):a(a){}

如果不使用构造函数初始化列表,则编译器将首先尝试初始化 A a; ,只有在为其分配了其他 a 之后,才尝试对其进行初始化.但是,第一次初始化失败,因为没有提供默认的构造函数.通常,建议在初始化成员时始终使用构造函数初始化列表.这样,您无需调用一个构造函数和一个赋值运算符,而只需调用复制构造函数.

If you don't use a constructor initialization list, then the compiler first tries to initialize A a;, and only after assigns the other a to it. However, the first initialization fails because there is no default constructor provided. In general, it is recommended to always using the constructor initialization list when initializing members. In this way, instead of calling one constructor + one assignment operator, you only call the copy constructor.

我建议将成员的名称从 a 更改为例如 _a ,因此代码变得更加清晰.

I suggest changing the name of the member from a to e.g. _a, so the code becomes a bit more clear.

这篇关于找不到默认的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆