对虚函数的引用

reference to virtual function

假设我有一个基础 class A 和派生的 classes 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'

帮忙?

所有虚函数都需要有一个定义(实现)。

我觉得不错。如果您只实例化继承的 class.

,则不需要在基础 class 中定义

它是什么编译器?

编译器会为每个class生成一个虚函数table(vtbl),指向class的所有虚函数的实现,对于[=17] =] A,它希望找到 A::b() 和 A::c().

的实现

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

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