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


我可能错了,但这可能只是问题所在:

阴影仅基于名称,而不是参数的类型。编译器观察到派生类中有一个具有正确名称的函数,它停止查找。选择了上下文后,它会在派生类中查找适用的重载,但没有找到,因此报告错误。

此处有更多详细信息
C++ 方法仅在对象转换为基类时可见?


C 类有一个 foo( void )

main()中使用:

test.foo(45);

您将int传递给foo函数,即使它是foo(void)
因此错误:

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 回答