簡體   English   中英

C ++構造函數和析構函數

[英]C++ Constructor and Destructor

我在編譯程序時遇到了一些錯誤。 它們與我的類指令的構造函數和析構函數有關。

錯誤是:

/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;
    }

我猜這個問題是由於你在Instruction類中聲明了一個虛擬方法'execute',並且從未在任何地方定義它。 編譯器必須為具有虛方法的類生成vtable對象,並且實際上只需要它的一個副本,因此它們通常只在定義第一個虛函數的編譯單元(源文件)中執行它。

你沒有定義你的虛函數和/或g ++想讓你的析構函數是虛擬的(因為你有假定繼承的虛函數)

嘗試

virtual void execute()=0;

這將使您的類抽象,這似乎是您想要的,因為未定義執行。

如果您想在多個.cpp文件中使用Instruction,則應將類方法的實現移動到classes.cpp文件中。

正如人們已經說過的那樣,問題是沒有實現execute()。 Dan Hook說,實施它,或者讓它變得純粹虛擬。

只是一個額外的評論:在很多(可能大多數取決於你編寫的內容)的情況下,你不需要實現析構函數。 如果您需要某些特定的功能(例如,將數據刷新到文件),您只需要。

只要您沒有指針(就像您的代碼中的情況一樣),您就不會有任何內存跟蹤問題。 只需刪除析構函數:它是安全的,而且代碼更少。 但是,如果只有一個成員是指針,那么一切都變得混亂,你必須處理內存管理問題,內存泄漏和段錯誤;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM