类继承出错
class inheritance erroring out?
我在尝试构建时遇到两组错误:
(在第一次构建时)
In constructor 'aa::aa(int)':
no matching function for call to 'bb:bb()'
candidates are: bb::bb(int)
bb:bb(const bb&)
(然后我再次点击构建并获得以下内容)
file not recognized: File truncated... takes me to assembly
collect2:ld returned 1 exit status
#ifndef BB_H
#define BB_H
class bb
{
public:
bb(int _m);
int m;
};
#endif // BB_H
#ifndef AA_H
#define AA_H
#include "AA/bb.h"
class aa : bb
{
public:
aa(int _i);
int i;
int j;
};
#endif // AA_H
#include "bb.h"
bb::bb(int _m)
{
m = _m * 5;
}
#include "aa.h"
aa::aa(int _i)
{
i = _i;
j = i + 1;
}
In constructor 'aa::aa(int)':
no matching function for call to 'bb:bb()'
编译器是对的。您没有默认的构造函数。即使编译器会为您编写默认构造函数(如果您不编写),但如果您有任何用户定义的构造函数,则不会发生这种情况。
你有两个选择:
首先,实现一个默认构造函数:
class bb
{
public:
bb(int _m);
bb();
int m;
};
bb:bb()
{
}
这可能很恶心,因为您将如何初始化m
?
其次,使用初始化列表调用aa
的构造函数中的convert构造函数:
aa::aa(int _i)
:
bb (_i)
{
i = _i;
j = i + 1;
}
基类构造函数在创建派生类对象时被调用
在您的示例中,您一定创建了一个aa类的对象,因为bb类是它的基类,所以编译器会搜索bb类的默认构造函数。由于您已经创建了一个参数化构造函数,它不会提供任何导致错误的默认构造函数
对bb()的函数调用没有匹配项
要克服这个错误,请在bb类中提供一个默认构造函数,如
bb::bb()
{
}
或
在aa构造函数初始化列表中,只需调用bb类参数化构造函数,如下所示
aa::aa(int i):bb(int x)
{
}
我在这里所做的是,在初始化派生类的数据成员之前,我刚刚初始化了基类的数据成员,编译器也希望如此。
相关文章:
- 继承函数的重载解析
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 继承期间显示未知行为的子类
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 在 c++ 中,当一个类继承头文件中的另一个类时出错
- 尝试从 C++ 中的构造函数从类继承时出错
- C++继承出错
- 使用继承C++时出错
- 从具有多个参数的模板类继承时出错
- 实例化没有继承的对象时出错
- 第一个帖子!对头文件使用继承时出错
- 在C++中继承类时出错:模板参数推导/替换失败
- 类继承出错
- 从模板类继承时出错
- 计算继承方法时出错
- C++ 继承:调用基类构造函数时出错 C2614