[英]Why doesn't derived templated class's function override the non-templated base class's pure virtual function?
[英]Why doesn't g++ complain when derived class calls pure virtual function of base?
我有一個帶有純虛函數f()
的類Base
。 另一個Derived
派生自Base
。 我從Derived
調用f()
。 使用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;
}
因為純虛函數可以有定義,如果有,你可以使用語法VirtualBase::f()
非虛擬地調用它們。
編譯器無法判斷您是否打算定義函數,因此只能由鏈接器檢測錯誤。
調用純虛函數不是錯誤。 調用任何沒有定義的函數是錯誤的。 純虛函數可以有一個定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.