chr*_*ock 9 c++ inheritance overloading name-hiding
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
};
Run Code Online (Sandbox Code Playgroud)
我可以B::foo()
轻松打电话:
B b;
b.foo (1, 2); // [1]
Run Code Online (Sandbox Code Playgroud)
但如果我试着打电话A::foo()
......
B b;
b.foo (12); // [2]
Run Code Online (Sandbox Code Playgroud)
...我收到编译器错误:
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)
Run Code Online (Sandbox Code Playgroud)
为了确保我没有遗漏某些东西,我改变了B
函数的名称,以便没有过载:
class B : public A {
int x2;
public:
void stuff (int y, int z) {x2 = y + z;} // unique name
};
Run Code Online (Sandbox Code Playgroud)
现在我可以A::foo()
使用第二个例子打电话.
这是标准吗?我正在使用g ++.
Jam*_*lis 18
您需要在类的定义中使用using声明B
:
class B : public A {
public:
using A::foo; // allow A::foo to be found
void foo(int, int);
// etc.
};
Run Code Online (Sandbox Code Playgroud)
如果没有using声明,编译器会B::foo
在名称查找期间找到并且实际上不会搜索具有相同名称的其他实体的基类,因此A::foo
找不到.
归档时间: |
|
查看次数: |
4258 次 |
最近记录: |