5

我有Base一个纯虚函数的类f()。另一个类Derived派生自Base. 我f()从内部呼叫Derived。并且使用 g++,我从链接器中得到一个错误。

[agnel@dooku tmp]$ g++ pure_virtual_function_call.cpp 
/tmp/ccGQLHi4.o: In function `Derived::f()':
pure_virtual_function_call.cpp:(.text._ZN7Derived1fEv[_ZN7Derived1fEv]+0x14): undefined reference to `VirtualBase::f()'
collect2: error: ld returned 1 exit status

在我看来,错误是由链接器捕获的。为什么编译器没有报告这个错误?为什么把它留给链接器?

这是代码:

#include <iostream>

using namespace std;

class VirtualBase {
public:
    virtual void f() = 0;
};

class Derived : public VirtualBase {
public:
    void f(){
        VirtualBase::f();
        cout << "Derived\n" ;
    }
};


int main(){
    Derived d;
    d.f();
    return 0;
}
4

2 回答 2

12

Because pure virtual functions can have definitions and, if they do, you are allowed to call them non-virtually using the syntax VirtualBase::f().

The compiler has no way to tell whether you intend the function to be defined or not, and so the error can only be detected by the linker.

于 2012-09-27T17:17:10.177 回答
8

调用纯虚函数不是错误。调用任何没有定义的函数都是错误的。纯虚函数可以有定义。

于 2012-09-27T17:15:31.143 回答