我可以在基础 class 中重载纯虚方法吗?
Can I overload pure virtual method in the base class?
在下面的示例中,我有一个抽象 class,其中包含纯虚方法(又名 FUN1)和普通方法(又名 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();
}
为什么我不能在派生 class 上调用 FUN2? g++ 报错:
main.cpp:19:8: error: no matching function for call to ‘B::fun()’
编辑:请注意 Overload of pure virtual function 问题不同。我不想覆盖方法。
尝试在 B class 中添加 using A::fun;
语句:
#include <iostream>
class A
{
public:
virtual void fun(int i) = 0; // FUN1
void fun() { this->fun(123); } // FUN2
};
class B : public A
{
public:
using A::fun;
virtual void fun(int i) { std::cerr << i << std::endl; }
};
int main(int, char**)
{
B b;
b.fun();
b.fun(5);
}
这是派生的 class 成员查找的工作方式:在表达式 b.fun()
中,首先在 class B
的范围内查找 fun
,查找发现B::fun(int)
。所以它停止并且永远找不到 A::fun()
.
标准的相关部分是 10.2 [class.member.lookup]/4:
If C
contains a declaration of the name f
, the declaration set contains every declaration of f
declared in
C
that satisfies the requirements of the language construct in which the lookup occurs. (...) If the resulting declaration set is not empty, the subobject set contains C
itself, and calculation is complete.
要使基础 class 函数可直接访问,您可以在派生的 class 中使用 using
声明,即 using A::fun;
.
对于在基础 class 中实现的方法,替代方法有时是有资格调用,即 b.A::fun()
。
在下面的示例中,我有一个抽象 class,其中包含纯虚方法(又名 FUN1)和普通方法(又名 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();
}
为什么我不能在派生 class 上调用 FUN2? g++ 报错:
main.cpp:19:8: error: no matching function for call to ‘B::fun()’
编辑:请注意 Overload of pure virtual function 问题不同。我不想覆盖方法。
尝试在 B class 中添加 using A::fun;
语句:
#include <iostream>
class A
{
public:
virtual void fun(int i) = 0; // FUN1
void fun() { this->fun(123); } // FUN2
};
class B : public A
{
public:
using A::fun;
virtual void fun(int i) { std::cerr << i << std::endl; }
};
int main(int, char**)
{
B b;
b.fun();
b.fun(5);
}
这是派生的 class 成员查找的工作方式:在表达式 b.fun()
中,首先在 class B
的范围内查找 fun
,查找发现B::fun(int)
。所以它停止并且永远找不到 A::fun()
.
标准的相关部分是 10.2 [class.member.lookup]/4:
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.
要使基础 class 函数可直接访问,您可以在派生的 class 中使用 using
声明,即 using A::fun;
.
对于在基础 class 中实现的方法,替代方法有时是有资格调用,即 b.A::fun()
。