我正在尝试做一个关于继承的项目,我收到了这个错误:
/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
这是我的代码:
主.cpp:
#include <iostream>
#include "Base.h"
#include "Derived.h"
int main() {
Derived intList(25);
}
基地.h:
#ifndef BASE_H
#define BASE_H
class Base {
public:
...
Base (const Base& otherList);
virtual ~Base();
protected:
int *list;
int length;
int maxSize;
};
#endif
基础.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