c++ - 虚函数的引用

标签 c++ reference undefined

假设我有一个基类 A 和派生类 B 和 C。 我希望能够通过 A 类型的引用指针执行派生函数的方法。 我尝试过使用虚拟函数:

class A
{
public:
    virtual std::string a() { return "a() of a"; }
    virtual std::string b();
    virtual std::string c();
};

class B : public A
{
public:
    std::string a() { return "a() of b"; }
    std::string b() { return "b() of b"; }
};

class C : public A
{
public:
    std::string a() { return "a() of c"; }
    std::string c() { return "c() of c"; }
};

int main(int argc, char** argv)
{
    B b;
    C c;

    A* a1 = &b;
    A* a2 = &c;

    std::cout << a1->b() << std::endl;
    std::cout << a2->c() << std::endl;

    return 0;
}

但我一直收到这个:

/tmp/ccsCMwc6.o:(.rodata._ZTV1C[_ZTV1C]+0x18): undefined reference to A::b()' /tmp/ccsCMwc6.o:(.rodata._ZTV1B[_ZTV1B]+0x20): undefined reference toA::c()' /tmp/ccsCMwc6.o:(.rodata._ZTI1C[_ZTI1C]+0x10): undefined reference to typeinfo for A' /tmp/ccsCMwc6.o:(.rodata._ZTI1B[_ZTI1B]+0x10): undefined reference to typeinfo for A'

帮忙?

最佳答案

编译器会为每个类生成一个虚函数表(vtbl),该表指向该类所有虚函数的实现,对于类 A,它期望找到 A::b() 和答::c()。

如果您不想实现它们,则需要将它们声明为纯虚拟:

class A
{
public:
    virtual std::string a() { return "a() of a"; }
    virtual std::string b() = 0;
    virtual std::string c() = 0;
};

关于c++ - 虚函数的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32298091/

相关文章:

jquery 数组返回一个未定义的?

Android CMake "fatal error: ' 位/libc-header-start.h' 找不到文件”

c++ - sqlite3_wal_checkpoint_v2 总是返回 SQL_BUSY

c++ - QMap 返回作为引用有问题吗?

javascript - 未定义 setOnLoadCallback 的 Google 可视化

Javascript Object.Property 日志记录未定义

c++ - 为什么 string::append 操作表现奇怪?

c++ - 无法使用 Boost.Filesystem 链接程序

xml - 如何从 XML::Simple 访问嵌套数据结构中的数据?

php - 将 create_function 用作闭包时从包含作用域引用变量。 PHP