0

重複の可能性:
C++ メソッドは、オブジェクトが基底クラスにキャストされたときにのみ表示される?!
派生クラスのオーバーライドされた関数が基底クラスの他のオーバーロードを隠すのはなぜですか?

#include <iostream>

using namespace std;

class A
{
public:
    virtual void foo(void) const { cout << "A::foo(void)" << endl; }
    virtual void foo(int i) const { cout << i << endl; }
    virtual ~A() {}
};

class B : public A
{
public:
    void foo(int i) const { this->foo(); cout << i << endl; }
};

class C : public B
{
public:
    void foo(void) const { cout << "C::foo(void)" << endl; }
};


int main(int argc, char ** argv)
{
    C test;

    test.foo(45);

    return 0;
}

上記のコードは、次のものではコンパイルできません。

$>g++ test.cpp -o test.exe
test.cpp: In member function 'virtual void B::foo(int) const':
test.cpp:17: error: no matching function for call to 'B::foo() const'
test.cpp:17: note: candidates are: virtual void B::foo(int) const
test.cpp: In function 'int main(int, char**)':
test.cpp:31: error: no matching function for call to 'C::foo(int)'
test.cpp:23: note: candidates are: virtual void C::foo() const

メソッド「foo(void)」を「goo(void)」に変更するとコンパイルされます。これはなぜですか?「foo(void)」のメソッド名を変更せずにコードをコンパイルすることはできますか?

ありがとう。

4

2 に答える 2

0

foo goo void int


私は間違っているかもしれませんが、これは問題かもしれません:

シャドウイングは、パラメーターのタイプではなく、名前のみに基づいています。コンパイラーは、正しい名前の関数がderieved-classにあることを確認し、検索を停止します。コンテキストを選択すると、derieved-classで適用可能なオーバーロードを探しますが、見つからないため、エラーを報告します。

詳細はこちら
C++メソッドは、オブジェクトが基本クラスにキャストされた場合にのみ表示されますか?


クラスCにはfoo(void)があります

main()で使用:

test.foo(45);

foo(void)であるにもかかわらず、intfoo関数に渡している ため、エラーが発生します。

test.cpp: In function 'int main(int, char**)':  
test.cpp:31: error: nomatching function for call to'C::foo(int)'

私は理にかなっていると思います。
これでしょうか??誰かコメント??..。

于 2010-04-22T05:27:20.627 に答える
0

問題は、継承が異なる名前空間に引き継がれないことです。したがって、コンパイルするには、using ディレクティブを使用してコンパイラに指示する必要があります。

class B : public A
{
public:
    using A::foo;
    void foo(int i) const { this->foo(); cout << i << endl; }
};

class C : public A
{
public:
    using B::foo;
    void foo(void) const { cout << "C::foo(void)" << endl; }
};
于 2010-04-22T05:35:23.460 に答える