【发布时间】:2011-06-03 13:54:31
【问题描述】:
C++ 标准中有什么东西阻止我重载超类的函数吗?
从这对类开始:
class A { // super class
int x;
public:
void foo (int y) {x = y;} // original definition
};
class B : public A { // derived class
int x2;
public:
void foo (int y, int z) {x2 = y + z;} // overloaded
};
我可以轻松拨打B::foo():
B b;
b.foo (1, 2); // [1]
但如果我尝试打电话给A::foo() ...
B b;
b.foo (12); // [2]
...我得到一个编译器错误:
test.cpp: In function 'void bar()':
test.cpp:18: error: no matching function for call to 'B::foo(int)'
test.cpp:12: note: candidates are: void B::foo(int, int)
为了确保没有遗漏任何内容,我更改了B 的函数名称,以免过载:
class B : public A {
int x2;
public:
void stuff (int y, int z) {x2 = y + z;} // unique name
};
现在我可以使用第二个示例调用A::foo()。
这是标准吗?我正在使用 g++。
【问题讨论】:
标签: c++ inheritance overloading name-hiding