我可以在基类中重载纯虚方法吗? [英] Can I overload pure virtual method in the base class?
问题描述
在下面的示例中,我有一个抽象类,其中包含纯虚拟方法(aka FUN1)和普通方法(aka FUN2).
In the example below I have a abstract class with pure virtual method (aka FUN1) and a normal method (aka FUN2).
#include <iostream>
class A
{
public:
virtual void fun(int i) = 0; // FUN1
void fun() { this->fun(123); } // FUN2
};
class B : public A
{
public:
virtual void fun(int i) { std::cerr << i << std::endl; }
};
int main(int,char**)
{
B b;
b.fun();
}
为什么不能在派生类上调用FUN2? g ++给出错误:
Why can't I call FUN2 on derived class? g++ gives an error:
main.cpp:19:8:错误:没有匹配的函数可以调用"B :: fun()"
main.cpp:19:8: error: no matching function for call to ‘B::fun()’
请注意,纯虚拟函数的重载问题是不同的.我不想重写方法.
note that Overload of pure virtual function question is different. I don't want to override methods.
推荐答案
这是派生类成员查找工作的方式:在表达式b.fun()
中,首先在class B
的范围内查找fun
,查找找到B::fun(int)
.因此它停止了,再也找不到A::fun()
.
This is how derived class member lookup works: in the expression b.fun()
, fun
is first looked up in the scope of class B
, and the lookup finds B::fun(int)
. So it stops and never finds A::fun()
.
该标准的相关部分为10.2 [class.member.lookup]/4:
Relevant section of the standard is 10.2 [class.member.lookup]/4:
如果
C
包含名称为f
的声明,则声明集包含在f
中声明的每个f
声明C
满足在其中进行查找的语言结构的要求. (...)如果结果声明集不为空,则子对象集本身包含C
,并且计算完成.
If
C
contains a declaration of the namef
, the declaration set contains every declaration off
declared inC
that satisfies the requirements of the language construct in which the lookup occurs. (...) If the resulting declaration set is not empty, the subobject set containsC
itself, and calculation is complete.
要直接访问基类函数,可以在派生类中使用using
声明,即using A::fun;
.
To make the base class function directly accessible you can use a using
declaration in the derived class, i.e. using A::fun;
.
对于在基类中实现的方法,有时可以选择调用b.A::fun()
.
For methods that are implemented in the base class an alternative is sometimes to qualify to call, i.e. b.A::fun()
.
这篇关于我可以在基类中重载纯虚方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!