【问题标题】:undefined reference to vtable when using interface使用接口时对 vtable 的未定义引用
【发布时间】:2015-03-16 18:40:59
【问题描述】:

我环顾四周,我不能完全弄清楚我哪里出错了,因为我在使用接口时似乎遵循了正确的约定,但也许我忽略了一些东西。我得到的确切错误是:

对 `vtable for Icommand' 的未定义引用

我才刚刚开始将我的类和类声明分离到单独的头文件中,所以我可能在某处缺少预处理器指令。

ma​​in.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(){}

标签: c++ inheritance interface polymorphism


【解决方案1】:

在 Icommand.h 中,替换

virtual std::string getCommand() const;

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

使其成为纯粹的虚拟。然后编译器可以为Icommand 生成一个vtable。或者,实现Icommand::getCommand

【讨论】:

  • 是的,这已经解决了问题,尽管我仍然难以理解为什么它需要是一个纯虚函数。我必须熟悉 vtables。
猜你喜欢
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
相关资源
最近更新 更多