c++继承名称隐藏
C++ inheritance name hiding
我对c++和继承有一个问题。希望有人能给我解释一下。
编译并运行以下代码:
struct Foo {
virtual ~Foo() {}
virtual unsigned int rnd1() = 0;
unsigned int rnd2(unsigned int limit) {
return rnd1() % limit;
}
};
struct Bar : public Foo {
Bar() : state(12345678) {}
unsigned int rnd1() {
return state = state * 1664525 + 1013904223;
}
private:
int state;
};
#include <cstdio>
void fooTest() {
Foo* r = new Bar();
printf("Foo->rnd2(16) = %un", r->rnd2(16));
delete r;
}
void barTest() {
Bar* r = new Bar();
printf("Bar->rnd2(16) = %un", r->rnd2(16));
delete r;
}
int main() {
fooTest();
barTest();
}
这里没有问题,因为rnd1
和rnd2
有不同的名称。如果rnd1
和rnd2
都重命名为rnd
,它将不再编译。下面的代码无法编译:
struct Foo {
virtual ~Foo() {}
virtual unsigned int rnd() = 0;
unsigned int rnd(unsigned int limit) {
return rnd() % limit;
}
};
struct Bar : public Foo {
Bar() : state(12345678) {}
unsigned int rnd() {
return state = state * 1664525 + 1013904223;
}
private:
int state;
};
#include <cstdio>
void fooTest() {
Foo* r = new Bar();
printf("Foo->rnd(16) = %un", r->rnd(16));
delete r;
}
void barTest() {
Bar* r = new Bar();
printf("Bar->rnd(16) = %un", r->rnd(16));
delete r;
}
int main() {
fooTest();
barTest();
}
下面是来自gcc的错误:ubuntu:~$ g++ -Wall -Wextra -pedantic test.cpp
test.cpp: In function ‘void barTest()’:
test.cpp:28:42: error: no matching function for call to ‘Bar::rnd(int)’
printf("Bar->rnd(16) = %un", r->rnd(16));
^
test.cpp:28:42: note: candidate is:
test.cpp:11:16: note: virtual unsigned int Bar::rnd()
unsigned int rnd() {
^
test.cpp:11:16: note: candidate expects 0 arguments, 1 provided
我的问题是:为什么c++不使用参数作为名称的一部分?在很多其他情况下都是这样,为什么现在不行呢?
如果你是真心的,请问一下。添加声明
using Foo::rnd;
到Bar
的公共部分。
默认情况下,如果您以某些名称提供方法,则隐藏相同名称但不同签名的方法。这是因为当您打算重写但使用了不正确的签名时,通常会错误地发生这种情况,并且如果发生这种情况,将很难检测到。
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 名称隐藏对静态函数继承的实例使用
- C++继承模板类:隐藏成员变量
- QScopedPointer 是否隐藏了多重继承
- 在继承的类构造函数中使用隐藏成员
- 使用私有继承来隐藏实现是个好主意吗
- C++隐藏继承的类
- 由多重继承隐藏的嵌套类
- 对继承的类隐藏的名称
- 具有不同签名的两个函数的继承隐藏了非虚函数
- 我如何使用接口隐藏我的实现,并且仍然使用继承构建类
- 为什么继承的函数隐藏在这个代码的基类中
- C++通过继承隐藏变量
- c++继承和名称隐藏
- 在c++中使用私有继承时是否可能隐藏重载方法?
- 访问隐藏的继承成员
- c++继承名称隐藏
- 部分隐藏的继承树
- 我如何使用 no除非我从继承列表中选择特定的隐藏函数