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()
easily:
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++。
您需要在类的定义中使用 using 声明B
:
class B : public A {
public:
using A::foo; // allow A::foo to be found
void foo(int, int);
// etc.
};
如果没有 using 声明,编译器会发现B::foo
在名称查找期间,实际上不会搜索基类以查找具有相同名称的其他实体,因此A::foo
没有找到。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)