【发布时间】:2026-01-22 09:20:04
【问题描述】:
编辑:与c++ undefined reference to `vtable相关
我正在尝试做一个关于继承的项目,但我收到了这个错误:
/tmp/ccw1aT69.o: In function `main':
main.cpp:(.text+0x15): undefined reference to `Derived::Derived(int)'
/tmp/ccw1aT69.o: In function `Derived::~Derived()':
main.cpp:(.text._ZN20DerivedD2Ev[_ZN20DerivedD5Ev]+0x13): undefined reference to `vtable for Derived'
main.cpp:(.text._ZN20DerivedD2Ev[_ZN20DerivedD5Ev]+0x1f): undefined reference to `Base::~Base()'
collect2: ld returned 1 exit status
这是我的代码:
main.cpp:
#include <iostream>
#include "Base.h"
#include "Derived.h"
int main() {
Derived intList(25);
}
base.h:
#ifndef BASE_H
#define BASE_H
class Base {
public:
...
Base (const Base& otherList);
virtual ~Base();
protected:
int *list;
int length;
int maxSize;
};
#endif
Base.cpp:
#include "Base.h"
#include <iostream>
using namespace std;
...definitions of my members...
Base::Base (int size) {
//stuff
}
Base::~Base() {
delete [] list;
}
Base::Base (const Base& otherList) {
//stuff
}
派生的.h:
#ifndef DERIVED_H
#define DERIVED_H
#include "Base.h"
class Derived: public Base {
public:
...
Derived (int size = 100);
~Derived(); //THIS LINE ADDED AFTER FIRST ANSWER
};
#endif
派生的.cpp:
#include "Derived.h"
#include <iostream>
using namespace std;
Derived::Derived (int size)
:Base(size){
}
是什么导致了这个错误?看起来我不能调用构造函数,但对我来说看起来不错。
编辑:我尝试了第一个解决方案。现在出错:
/tmp/ccA4XA0B.o: In function `main':
main.cpp:(.text+0x15): undefined reference to `Derived::Derived(int)'
main.cpp:(.text+0x21): undefined reference to `Derived::~Derived()'
collect2: ld returned 1 exit status
【问题讨论】:
-
请发布真实代码“private void Derived::quickSort()` 无效。C++ 不是 Java。另外,请发布 minimal 代码。构造函数和问题析构函数通常不需要derived.cpp 中的所有内容,我不得不滚动几次才能看到
Derived::Derived(int)没有定义。 -
非常抱歉所有代码...我不确定需要什么。
-
请包含 Base.cpp,因为您在源列表中包含了两次 Base.h; Base.h 一次,base.cpp 一次。只有这样我们才能看到 Base::~Base() 是否被正确定义(最好是,因为它是在标题中声明的。
-
请注意,使用包含析构函数定义的新编辑,您现在已经破坏了The Rule of Three,并且很快就会遇到段错误(希望如此!)。
-
这是我有点困惑的地方——我已经定义了所有三个,但是由于它们是虚拟的,所以我的继承类必须再次定义它们,对吧?
标签: c++ constructor undefined-reference