0

尝试构建时出现两组错误:

(在第一次构建时)

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

2 回答 2

3
In constructor 'aa::aa(int)':
no matching function for call to 'bb:bb()'

编译器是对的。您没有默认构造函数。即使编译器会为您编写一个默认构造函数(如果您不编写),但如果您有任何用户定义的构造函数,则不会发生这种情况。

您有 2 个选择:

首先,实现一个默认构造函数:

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;
}
于 2013-07-12T17:31:39.307 回答
0

创建派生类对象时调用基类构造函数。
在您的示例中,您必须创建了一个类 aa 的对象,因为类 bb 是它的基类,编译器搜索 bb 类的默认构造函数。由于您创建了参数化构造函数,因此它不会提供任何默认构造函数,从而导致错误
No matching for the function call to bb()。
为了克服该错误,请在 bb 类中提供默认构造函数,例如

    bb::bb()
    {
    } 



在 aa 构造函数初始化列表中,只需调用类 bb 参数化构造函数,如下所示

    aa::aa(int i):bb(int x)
    {
    }  


我在这里所做的是,在初始化派生类的数据成员之前,我刚刚初始化了基类的数据成员,并且编译器期望相同。

于 2013-07-12T19:08:07.147 回答