gpt4 book ai didi

c++ - 使用接口(interface)时对 vtable 的 undefined reference

转载 作者:搜寻专家 更新时间:2023-10-31 01:02:00 24 4
gpt4 key购买 nike

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

undefined reference to `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

命令.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;}

最佳答案

在Icommand.h中,替换

virtual std::string getCommand() const;

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

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

关于c++ - 使用接口(interface)时对 vtable 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28013108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com