派生类通过基类定义函数 [英] Derived class defines function via base class
本文介绍了派生类通过基类定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
struct A
{
virtual void f() = 0;
};
struct B
{
void f();
};
struct C : public A, public B
{};
int main()
{
A* a = new C();
B* b = new C();
C* c = new C();
// All these calls should result in B::f
a->f();
b->f();
c->f();
}
编译器指出C
是抽象的.
如何解决这种情况?
这个问题似乎与钻石继承相似,但是我看不到解决方案.
The compiler states that C
is abstract.
How can this situation be resolved?
The issue seems similar to diamond inheritance, but I fail to see the solution.
谢谢,这是工作示例:
#include "stdio.h"
struct A
{
virtual void f() = 0;
};
struct B
{
void f()
{
printf("B::f\n");
}
};
struct C : public A, public B
{
void f()
{
printf("C::f\n");
B::f();
}
};
int main()
{
A* a = new C();
B* b = new C();
C* c = new C();
printf("Calling from A\n");
a->f();
printf("Calling from B\n");
b->f();
printf("Calling from C\n");
c->f();
}
输出:
Calling from A
C::f
B::f
Calling from B
B::f
Calling from C
C::f
B::f
推荐答案
问题在于,两个f()
函数完全不相关,即使它们恰好具有相同的名称.
The issue is that the two f()
functions are completely unrelated, even though they happen to have the same name.
如果所需的行为是C
的virtual
f()
调用B::f()
的行为,则必须明确地做到这一点:
If the desired behaviour is for the C
's virtual
f()
to call B::f()
, you have to do it explicitly:
struct C : public A, public B
{
void f();
};
void C::f() {
B::f();
}
这篇关于派生类通过基类定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文