c++ - 体系结构 x86_64 的 undefined symbol (C++ 继承问题)

标签 c++ class inheritance abstract-class virtual-functions

这是我在编译时遇到的错误:

Undefined symbols for architecture x86_64:
  "typeinfo for BaseClass", referenced from:
      typeinfo for DerivedOne in base-49c1cd.o
      typeinfo for DerivedTwo in base-49c1cd.o
  "vtable for BaseClass", referenced from:
      BaseClass::BaseClass() in base-49c1cd.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [test] Error 1

这是base.h:

class BaseClass {
public:
    // an enum
protected:
    float variable
public:
    float getVariable();
    void printBase();
    virtual BaseClass* clone();
    virtual float calculate(bool _one, bool _two) = 0;
};

class DerivedOne: public BaseClass {
public:
    DerivedOne(float _variable);
    BaseClass* clone();
    float calculate(bool _one, bool _two);
};

class DerivedTwo: public BaseClass {
public:
    DerivedTwo(float _variable);
    BaseClass* clone();
    float calculate(bool _one, bool _two);
};

base.cpp:

#include "base.h"

float BaseClass::getVariable() {
    return variable;
}

void BaseClass::printBase() {
    return; // not implemented yet
}

DerivedOne::DerivedOne(float _variable) {
    variable = _variable;
}

BaseClass* DerivedOne::clone() {
    DerivedOne* tmp = new DerivedOne(variable);
    return tmp;
}

float DerivedOne::calculate(bool _one, bool _one) {
    float val = //some calculation;
    return val;
}

DerivedTwo::DerivedTwo(float _variable) {
    variable = _variable;
}

BaseClass* DerivedTwo::clone() {
    DerivedTwo* tmp = new DerivedTwo(variable);
    return tmp;
}

float DerivedTwo::calculate(bool _one, bool _two) {
    float val = //some calculation;
    return val;
}

我已经更改了变量的名称,所以我可能打错了字。

我认为我遇到的问题源于我对构造函数和抽象类缺乏了解。谁能帮我解决问题?

最佳答案

您没有提供 BaseClass:clone 方法的实现。使其成为纯虚拟的,即 =0 或提供实现。

错误消息基本上说明了整个故事:

NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.

您提供了声明,但未提供定义。

关于c++ - 体系结构 x86_64 的 undefined symbol (C++ 继承问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26309135/

相关文章:

Python - 动态导入后未定义的类名

java - 我类(class)的数据为空?

c++ - 使用 ostream_iterator 和运算符 << 显示指针 vector

c++ - QPlainTextEdit - 搜索文档到最后,然后再从头开始

c++ - 在编译时使用 C++ 模板在 AbstractFactory 中动态注册构造方法

c++ - 为要在 1 类中使用的结构成员分配常量值

javascript - 为什么我不能覆盖类(函数)描述中的方法定义?

c++ - 在 OMNeT++ 中使用多重继承时是否存在任何已知问题?

C++ 重写方法不起作用

c++ - 通过元编程选择函数