【发布时间】:2010-04-22 05:09:06
【问题描述】:
可能的重复:
C++ method only visible when object cast to base class?!
Why does an overridden function in the derived class hide other overloads of the base class?
#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)”的方法名是否可以编译代码?
谢谢。
【问题讨论】:
-
另外,最后一个副本由于某种原因被删除了。不要删除重复项,它们会在查找预先存在的问题时提供更多关键字来搜索:/
-
我不知道要搜索的正确关键字。插入“使用 A::foo;”进入 B 类并“使用 B::foo;”进入C类解决了这个问题。第二个链接对名称隐藏有最好的解释。谢谢。
-
没问题,搜索可能很困难。 :)
标签: c++ inheritance overloading dynamic-binding