gpt4 book ai didi

C++ 继承问题 : undefined reference to 'vtable'

转载 作者:行者123 更新时间:2023-11-30 02:21:28 63 4
gpt4 key购买 nike

全部!我正在尝试使用 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;
}

基础.cpp

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

virtual void Base::show() {
cout << "printed in 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

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

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

关于C++ 继承问题 : undefined reference to 'vtable' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48274562/

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