[英]C++ Virtual Methods: Must I create a virtual method in the parent class for every method that the child and parent do not share?
[英]C++ Compiler (cl) does not see parent virtual method with same child method name
我有一個C ++代碼,同時使用繼承和函數重寫,這是代碼:
#include <iostream>
#include <string>
using namespace std;
class Parent
{
protected:
virtual void G() const = 0;
public:
virtual void G(const string& s) const final { G(); }
};
class Child : public Parent
{
protected:
virtual void G() const override { cout<<"Child G"; }
};
int main()
{
Child *c = new Child();
c->G("test");
return 0;
}
編譯時出現錯誤: Child::G: function does not take 1 arguments
。 但是當我像這樣使用Parent指針時:
Parent *c = new Child();
有用。 另外,如果我更改公共G
方法的名稱,它也可以工作。
兩種方法使用相同的名稱( G
)有什么問題?
您需要using
聲明將父成員介紹給孩子:
class Child : public Parent
{
protected:
virtual void G() const override { cout<<"Child G"; }
public:
using Parent::G;
};
解決此問題的方法的確是using
聲明指出,將Parent
的方法通過using
聲明引入Child
類的范圍。 至於為什么會這樣,僅是編譯器在搜索與您的函數調用匹配的方法時如何在范圍內搜索的問題。 發生的情況如下:
Child *c = new Child(); c->G("test");
Child *c = new Child(); c->G("test");
,編譯器會看到對Child
類型的對象的某些方法G
的調用。 然后,它搜索Child
的范圍以查找匹配項。 Child
的范圍時,僅看到Child::G() const
。 它沒有看到Parent::G(const std::string&) const
,即使您希望通過繼承將其包含在內,也處於不同的范圍內 。 從某種意義上說, Child::G
遮蓋了 Parent::G
沒有候選者匹配,編譯器將一直在搜索Parent
范圍。 Child::G
但是,此函數不接受任何參數,因此您嘗試使用"test"
對其進行調用。 然后,由於參數不匹配,函數調用失敗。 如前所述,您需要將Parent::G
置於與Child::G
相同的作用域內,以便按預期進行重載,並在Child
體內using Parent::G
資料來源: https : //isocpp.org/wiki/faq/strange-inheritance#overload-derived
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.