使用接口时出现undefined reference to vtable错误

4

我已经查看了一些资料,但是还无法确定我的错误在哪里,因为我似乎遵循了正确的接口使用惯例,但可能我忽略了某些东西。我收到的确切错误信息是:

undefined reference to `vtable for Icommand'

我只是开始将我的类和类声明分别放在不同的头文件中,所以可能我错过了某个预处理器指令。

main.cpp:

#include <iostream>
#include <string>
#include <cstdlib>
#include "Icommand.h"

#include "Command.h"

using namespace std;

void pause();

int main(){


    Icommand *run = new Command("TEST");
    cout << run->getCommand() << endl;
    delete run;

    pause();
}

void pause(){
    cin.clear();
    cin.ignore(cin.rdbuf()->in_avail());
    cin.get();
}

Icommand.h:

#ifndef ICOMMAND_H
#define ICOMMAND_H

#include <string>
#include <vector>


class Icommand
{
    private:

    public:
        Icommand(){}
        virtual ~Icommand(){}
        virtual bool run(std::string object1) = 0;
        virtual bool run(std::string object1, std::string object2) = 0;
        virtual std::string getCommand() const;
};



#endif // ICOMMAND_H

Command.h:

#ifndef COMMAND_H
#define COMMAND_H

#include <string>
#include <vector>

#include "Icommand.h"

class Command : public Icommand {

    private:
        std::string command;
        std::vector<std::string> synonymns;
        Command(); // private so class much be instantiated with a command

    public:
        Command(std::string command) : command(command){}
        ~Command(){}
        bool run(std::string object1);
        bool run(std::string object1, std::string object2);
        std::string getCommand() const;


};
#endif // COMMAND_H

Command.cpp:

#include <string>
#include <vector>

#include "Command.h"

bool Command::run(std::string object1){
    return false;
}
bool Command::run(std::string object1, std::string object2){
    return false;
}
std::string Command::getCommand() const {return command;}

你需要 virtual ~Command(){} - πάντα ῥεῖ
1个回答

8
在Icommand.h中,替换掉
virtual std::string getCommand() const;

使用

virtual std::string getCommand() const = 0;

将其改为纯虚函数。然后编译器可以为Icommand生成虚函数表。或者实现Icommand::getCommand


2
是的,这解决了问题,尽管我仍然难以理解为什么它需要成为一个纯虚函数。我需要熟悉vtable。 - Martyn Shutt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接