C++ 继承问题:对 'vtable' 的未定义引用

c++ inheritance issues: undefined reference to 'vtable'

全部!我正在尝试使用 C++ 和头文件创建一个非常简单的继承结构,但是(当然)我遇到了一些困难。

当我尝试编译我的主程序时,我得到这个错误:

In function `Base::Base()':
undefined reference to 'vtable for Base'
In function `Derived::Derived()':
undefined reference to 'vtable for Derived'

我只想打印

printed in Derived

但我遇到了一些极端的困难。

这是我的程序文件:

main.cpp

#include <iostream>
#include "Base.h"
#include "Derived.h"

using namespace std;

int main(void) {
    Base *bp = new Derived;
    bp->show();
    return 0;
}

Base.cpp

#include <iostream>
#include "Base.h"

virtual void Base::show() {
    cout << "printed in Base";
}

Base.h

#ifndef BASE_H
#define BASE_H

class Base {
    public:
        virtual void show();
};

#endif

Derived.cpp

#include <iostream>
#include "Derived.h"

using namespace std;

void Derived::show() override {
    cout << "printed in Derived";
}

Derived.h

#ifndef DERIVED_H
#define DERIVED_H

class Derived: public Base {
    public:
        void show() override;
};

#endif

谢谢!非常感谢任何帮助!...非常感谢。

正如评论中指出的那样,通过调用 g++ main.cpp 你只是在编译 main.cpp

您需要编译所有文件,然后link将它们一起编译。如果这样做,您会发现其他 cpp 文件中存在编译问题,正如评论中所指出的那样(virtual 和 override only belong in the header)。

所以你需要调用下面的命令来编译所有文件: g++ main.cpp Base.cpp Derived.cpp -o myapp