為什麼必須實現虛解構函式 ,純虛解構函式的原因
阿新 • • 發佈:2019-02-01
本文的主要參考書籍是 C++ Primer
struct A {
virtual ~A() = 0;
};
struct B : A {
virual ~B() {}
};
int main( void ) {
B x;
}
編譯的時候肯定報A::~A未實現,這是因為普通virtual只調用動態型別的那個函式實現,所以基類的可以不實現;而virtual解構函式則不同,它需要由下往上層層呼叫,所以每一層都需要實現。 另外,有沒有實現程式碼 跟 是否為純虛 是沒有關係的,只要把 A 改為: struct A { virtual ~A() = 0 {} };
看看下面的解釋:
A destructor can be declared virtual(10.3) or pure virtual(10.4);if any object of that class or any derived class are created in the program, the destructor shall be defined. If a class has a base
class with a virtual destructor, its destructor (whether user-or implicitly-declared) is virtual.
struct A { virtual ~A() = 0 {} }; 應當寫成 struct A { virtual ~A() = 0; }; A::~A() { }
因為C++規定 =0 和 {} 不能同時出現。
[Note: a function declaration cannot provide both a pure-specifier and a definition
—end note]
[Example:
struct C {
virtual void f() = 0 { }; // ill-formed
};
—end example]
必須實現虛解構函式 ,純虛解構函式的原因 大致如上!