C++继承问题: "undefined reference to"

3
在c++中练习继承时,我一直遇到以下错误:
base1.o: 在函数“Base1::Base1()”中: base1.cpp:(.text+0x75): 未定义对“Base2::Base2()”的引用 base1.o: 在函数“Base1::Base1()”中: base1.cpp:(.text+0xa5): 未定义对“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更改为:
#include <QStringList>
#include <QTextStream>
#include "base2.h"

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


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

然而,我仍然遇到了相同的错误。我认为这一定与“#include”有关,但我不知道如何正确使用它 :(。

4个回答

2
非常简单:您声明了Base2(),但从未定义它。即使它是空的,您也必须定义它...或者根本不声明它,那么将为您生成一个空的定义。
也许在base2.cpp中,Base1::Base1()应该改为Base2::Base2()child.cpp不应该有任何这些定义。 编辑:您说您仍然遇到问题。
我假设您注意到了上面的内容,并从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或其他自动化构建过程的结果)。

谢谢,所以我将base2.cpp更改为 Base2::Base2() { cout << "\nB2\n\n" << flush;
} 但是我仍然得到相同的错误 :(
- Anselm
@Anselm:错误一定是不同的。你有没有读懂我关于child.cpp的说明并查看链接?请看我的修改。 - Lightness Races in Orbit

2
您尚未实现。
Base2::Base2();

但是你已经使用过它。这就是为什么会出现未定义的引用(链接错误)。

在base2.cpp中,将Base1 :: Base1()替换为Base2 :: Base2(),问题就会解决。

使用更加清晰的名称以防止这些错误。


你说得对,我应该使用更清晰的名称,我以为这个小测试用例没关系... - Anselm
@AbiusX:什么?他使用 #ifdef 头文件保护非常完美。它们不应该出现在 .cpp 文件中。你认为有什么问题吗?此外,你的教学风格阻碍了学生学习基本的调试技巧,这真是太可惜了。 - Lightness Races in Orbit
@Tomalak 包含应该在 guard 内部而不是外部进行。 - AbiusX
@AbiusX:不,你错了。看这里:http://codepad.org/9SbrgdDe。我已经在base1.h和base2.h中使用了守卫,但仍然没有在someLib.h中加入。 - Lightness Races in Orbit
@AbiusX:你的学生们损失了。 - Lightness Races in Orbit
显示剩余10条评论

2
很可能是打字错误,但在base2.cpp中应该使用Base2::Base2()而不是Base1::Base1()

2

您在三个.cpp文件中定义了Base1::Base1(),而没有定义Base2::Base2()

您需要确保每个成员函数只被定义一次。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接