我有一个带有两个重载函数的基类f(void)
and f(int)
。班上Derived
实施f(int)
通过致电f(void)
. Derived2
实施f(void)
only.
编译器拒绝执行Derived::f(int)
因为它想打电话f(int)
但我没有提供任何论据,因为我想打电话f(void)
。为什么编译器会拒绝它?为什么添加行virtual int f(void) = 0;
解决我的问题吗?
class Base
{
public:
explicit Base(void) {}
virtual ~Base(void) {}
virtual int f(void) = 0;
virtual int f(int i) = 0;
};
class Derived : public Base
{
public:
// provide implementation for f(int) which uses f(void). Does not compile.
virtual int f(int i) {puts("Derived::f(int)"); return f();}
// code only compiles by adding the following line.
virtual int f(void) = 0;
};
class Derived2 : public Derived
{
public:
// overwrite only f(void). f(int) is implemented by Derived.
virtual int f(void) {puts("Derived2::f(void)"); return 4;}
};
int main(void)
{
Base * p = new Derived2();
int i0 = p->f(); // outputs Derived2::f(void) and returns 4
int i1 = p->f(1); // outputs "Derived::f(int) Derived2::f(void)" and return 4
delete p;
return 0;
}
Derived::f
hides Base::f
s。给定return f();
在体内Derived::f(int)
, 名字f
发现在范围内Derived
, then 姓名查询停止。中的名字Base
不会被发现并参与重载决策。
名称查找按如下所述检查范围,直到找到至少一个任何类型的声明,此时查找停止并且不再检查其他范围。
你可以加using Base::f;
介绍名字来自Base
纳入范围Derived
.
class Derived : public Base
{
public:
using Base::f;
// provide implementation for f(int) which uses f(void).
virtual int f(int i) {puts("Derived::f(int)"); return f();}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)