簡體   English   中英

C ++編譯器(cl)看不到具有相同子方法名稱的父虛擬方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM