编译程序时遇到一些错误。它们与我的课程的构造函数和析构函数有关。
错误是:
/tmp/ccSWO7VW.o: In function `Instruction::Instruction(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)':
ale.c:(.text+0x241): undefined reference to `vtable for Instruction'
/tmp/ccSWO7VW.o: In function `Instruction::Instruction(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)':
ale.c:(.text+0x2ab): undefined reference to `vtable for Instruction'
/tmp/ccSWO7VW.o: In function `Instruction::~Instruction()':
ale.c:(.text+0x315): undefined reference to `vtable for Instruction'
/tmp/ccSWO7VW.o: In function `Instruction::~Instruction()':
ale.c:(.text+0x38d): undefined reference to `vtable for Instruction'
collect2: ld returned 1 exit status
这是我的代码:
//classses.h
#include <iostream>
#include <string>
using namespace std;
class Instruction{
protected:
string name;
int value;
public:
Instruction(string _name, int _value);
~Instruction();
void setName(string _name);
void setValue(int _value);
string getName();
int getValue();
virtual void execute();
};
//constructor
Instruction::Instruction(string _name, int _value){
name = _name;
value = _value;
}
//destructor
Instruction::~Instruction(){
name = "";
value = 0;
}
void Instruction::setName(string _name){
name = _name;
}
void Instruction::setValue(int _value){
value = _value;
}
string Instruction::getName(){
return name;
}
int Instruction::getValue(){
return value;
}
/////////////////////////////////////////////// //////////////////////
//ale.cpp
#include "headers.h"
#include "functions.h"
#include "classes.h"
#include <list>
using namespace std;
int main(){
return 0;
}
答案 0 :(得分:8)
我猜这个问题是由于你在Instruction类中声明了一个虚拟方法'execute',并且从未在任何地方定义它。编译器必须为具有虚方法的类生成vtable对象,并且实际上只需要它的一个副本,因此它们通常只在定义第一个虚函数的编译单元(源文件)中执行...
答案 1 :(得分:5)
你没有定义你的虚函数和/或g ++想让你的析构函数是虚拟的(因为你有假定继承的虚函数)
答案 2 :(得分:3)
尝试
virtual void execute()=0;
这会使你的类变得抽象,这似乎是你想要的,因为没有定义执行。
如果你想在多个.cpp文件中使用Instruction,你应该将类方法的实现移到classes.cpp文件中。
答案 3 :(得分:0)
正如人们已经说过的那样,问题是没有实现execute()。正如Dan Hook所说,实现它,或者使它变得纯粹虚拟。
只是一个额外的评论:在很多(可能大多数取决于你编写的内容)案例中,你不需要实现析构函数。如果你想要一些特定的功能(例如将数据刷新到文件),你只需要。
只要您没有指针(就像代码中的情况一样),您就不会有任何内存跟踪问题。只需删除析构函数:它是安全的,而且代码更少。 但是,如果只有一个成员是指针,那么一切都变得混乱,你必须处理内存管理问题,内存泄漏和段错误;)