对Base :: run()的未定义引用;

时间:2014-10-01 20:45:02

标签: c++ gcc map

我的类Base有方法const char ** run,没有内容定义, 我有类Derived with方法const char ** run。 我有以下代码:

class Base { // in 'base.h'
    public:
        const char** run();
};
class Derived : public Base { // in 'derived.h'
    public:
        const char** run();
};
const char** Wsiv::run(){ // in 'derived.cpp'
    return something;
};
// IN 'main.cpp':
map<string, unique_ptr<Base>> modules;
modules["drvd"] = (unique_ptr<Base>(new Derived()));
// A little bit later...
string command = argv[1];
result = (*modules[command].get()).run();

而不是执行run()函数并将const char**输出存储到&#39;结果&#39;,程序不会编译,并且mingw g ++给了我这个错误:

C:/Users/bob/AppData/Local/Temp/ccc0cwsT.o:main.cpp:(.text+0x4ee): Undefined reference to 'Base::run()'
collect2.exe: error: ld returned 1 exit status

我的编译命令如下:

g++ ../src/*.cpp -o test -std=c++11

1 个答案:

答案 0 :(得分:3)

您实际上没有定义 run()所做的事情;你只是宣布它。

在您的示例中,您定义的Wsiv::run()未实现Base::run() Derived::run()。如果你想在一个子类中实现Base::run(),你必须告诉编译器在其他地方寻找它的定义。

这是virtuals发挥作用的地方。

virtual const char** run() {};

上面说的我可能在子类中实现,但我有一个默认的实现

virtual const char** run() = 0;

以上称为pure virtual,表示必须在子类中实现;我有默认实现;直到我在某处实现(例如,在子类中),我未定义


由于您的示例没有,因此编译器在调用Base::run()时不知道跳转到的位置。定义它,或将其声明为虚拟。