[英]Pure virtual functions with arguments of the same class
我很感激,如果有人能告訴我這里發生了什么:說我宣布以下內容
class Base {
public:
virtual void member(Base b) = 0;
};
這給出了以下編譯器錯誤:
pvf.cpp:3:18: error: cannot declare parameter ‘b’ to be of abstract type ‘Base’
virtual void member(Base b) = 0;
^
pvf.cpp:1:7: note: because the following virtual functions are pure within ‘Base’:
class Base {
^
pvf.cpp:3:18: note: virtual void Base::member(Base)
virtual void member(Base b) = 0;
但是,如果我通過引用傳遞,它編譯沒有問題:
class Base {
public:
virtual void member(Base& b) = 0;
};
此外,我想在派生類中實現member()
class Base {
public:
virtual void member(Base& b) = 0;
};
class Derived : public Base {
public:
void member(Derived& d) {};
};
int main() {
Derived d;
}
但是,(顯然?)我明白了
pvf.cpp: In function ‘int main()’:
pvf.cpp:12:14: error: cannot declare variable ‘d’ to be of abstract type ‘Derived’
Derived d;
^
pvf.cpp:6:8: note: because the following virtual functions are pure within ‘Derived’:
class Derived : public Base {
^
pvf.cpp:3:15: note: virtual void Base::member(Base&)
virtual void member(Base& b) = 0;
你的第一個功能
virtual void member(Base b) = 0;
獲取類Base
的參數值,該參數需要將Base
的實例傳遞給它。 但由於Base
是一個抽象類(因為它包含一個純虛函數),因此無法實例化它,因此您無法創建Base
的實例來傳遞給它! 這是你第一次出錯的原因。
在第二種情況下,在派生類中聲明一個函數
void member(Derived& d) {};
您可能認為會覆蓋基類虛函數
virtual void member(Base& b) = 0;
但事實並非如此(它實際上隱藏了它 - 請參閱為什么虛擬函數被隱藏?對此進行解釋),因此Derived
仍然是抽象類,因為您沒有在基類中提供純虛函數的實現。 出於這個原因, Derived
也無法實例化。 無法為基類純虛函數提供實現的派生類將像基類一樣保持抽象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.