C++构造函数和析构函数

use*_*514 2 c++ constructor destructor g++

我在编译程序时遇到了一些错误.它们与我的类指令的构造函数和析构函数有关.

错误是:

/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
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

//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;
}
Run Code Online (Sandbox Code Playgroud)

////////////////////////////////////////////////// ///////////////////

//ale.cpp

    #include "headers.h"
    #include "functions.h"
    #include "classes.h"
    #include <list>


    using namespace std;

    int main(){

    return 0;
    }
Run Code Online (Sandbox Code Playgroud)

Chr*_*odd 8

我猜这个问题是由于你在Instruction类中声明了一个虚拟方法'execute',并且从未在任何地方定义它.编译器必须为具有虚方法的类生成vtable对象,并且实际上只需要它的一个副本,因此它们通常只在定义第一个虚函数的编译单元(源文件)中执行它.


Dmi*_*try 5

你没有定义你的虚函数和/或g ++想让你的析构函数是虚拟的(因为你有假定继承的虚函数)

  • 顺便说一句,在析构函数中分配空字符串或零是没有意义的.其目的是销毁数据,而不是重新初始化数据.在你的情况下,空的析构函数就足够了 (2认同)