c ++继承问题“未定义引用”

时间:2011-03-15 00:23:12

标签: c++ inheritance

在c ++中练习继承时,我一直收到以下错误:

base1.o:在函数Base1::Base1()': base1.cpp:(.text+0x75): undefined reference to Base2 :: Base2()' base1.o:在函数Base1::Base1()': base1.cpp:(.text+0xa5): undefined reference to Base2 :: Base2()' collect2:ld返回1退出状态 make: * [test]错误1

我删除了所有不必要的代码,只剩下这个:

base1.h

#include "base2.h"
#ifndef BASE1_H_
#define BASE1_H_

class Base1 : public Base2 {  

public:
Base1();   
};

#endif

base1.cpp

#include <QStringList>
#include <QTextStream>
#include "base1.h"
#include "base2.h"

QTextStream cout(stdout);
QTextStream cin(stdin);

Base1::Base1() : Base2() {
cout << "\nB1\n\n" << flush;
}

base2.h

#ifndef BASE2_H_
#define BASE2_H_

class Base2 {

public:
Base2();
};

#endif

base2.cpp

#include <QStringList>
#include <QTextStream>
#include "base2.h"

QTextStream cout(stdout);
QTextStream cin(stdin);


Base1::Base1() {
cout << "\nB2\n\n" << flush;   
}

child.cpp

#include <QStringList>
#include <QTextStream>
#include "base1.h"
#include "base2.h"

QTextStream cout(stdout);
QTextStream cin(stdin);


Base1::Base1() {
cout << "\nB2\n\n" << flush;
}

这可能是一个简单的问题,但我花了2个小时在谷歌上寻找解决方案并且没有找到任何东西,所以我将不胜感激任何帮助。


嗨,

感谢大家到目前为止的答案。

我改变了 base2.cpp to:

#include <QStringList>
#include <QTextStream>
#include "base2.h"

QTextStream cout(stdout);
QTextStream cin(stdin);


Base2::Base2() {
cout << "\nB2\n\n" << flush;
}

然而,我仍然得到同样的错误。我认为它必须与“#include”有关,但我不知道该怎么做:(。

4 个答案:

答案 0 :(得分:2)

非常简单:您声明Base2()但从未定义它。你必须,即使它是空的......或者根本没有声明它,并且会为你生成一个空的。

base2.cpp中的Base1::Base1()或许应该是Base2::Base2()

child.cpp shouldn't have definitions for any of them.

编辑你说你还有问题。

我将假设您已注意到上述内容并从child.cpp中删除了Base1::Base1()的无关定义。

您是如何构建项目的?应该是这样的:

 g++ base1.cpp base2.cpp child.cpp -o myProgram

或者喜欢:

 g++ base1.cpp -o base1.o
 g++ base2.cpp -o base2.o
 g++ child.cpp -o child.o
 g++ base1.o base2.o child.o -o myProgram

(通常是使用makefile或其他自动构建过程的结果)。

答案 1 :(得分:2)

可能是一个拼写错误,但在2.c ++基础上它应该说Base2::Base2()而不是Base1::Base1()

答案 2 :(得分:2)

您已在三个.cpp文件中定义了Base1::Base1(),并且根本没有定义Base2::Base2()

您需要完全定义每个成员函数一次

答案 3 :(得分:2)

您尚未实施

Base2::Base2();

但你已经习惯了。这就是它未定义的引用(链接错误)

的原因

在base2.cpp中用Base2 :: Base2()替换Base1 :: Base1(),它将修复。

使用更明智的名称来防止这些错误。