我只是偶然发现了一个编译错误,我想知道为什么发生这种情况。
代码:虚拟功能通过多个接口访问
struct Foo1
{
virtual int foo() = 0;
};
struct Foo2 : Foo1
{
virtual int foo(int i) = 0;
};
struct Bar : public Foo2
{
virtual int foo() { return 0; }
virtual int foo(int i) { return i; }
};
int main() {
Bar b;
Foo2* f2 = &b;
b.foo();
//f2->foo(); // this gives an error
return 0;
}
误差在GCC 4.8.1是
error: no matching function for call to ‘Foo2::foo()’
我很奇怪,为什么编译器无法看到Foo1::foo
功能? 我知道我可以通过在Foo2
类中添加using Foo1::foo
来解决这个问题,但任何人都可以给我一个参考标准,为什么编译器无法自己找到函数?
这是正确的答案。这种现象也被称为“名称隐藏”IIRC,基本上声明如果在派生类中存在具有相同名称的声明,则隐藏基类中的声明。这是设计来避免一些“人为的”行为。 –