从继承的类实现抽象方法 [英] Implement abstract methods from inherited class

查看:198
本文介绍了从继承的类实现抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做以前从未真正做过的事情.我基本上有3节课.类A是具有纯虚拟方法的抽象类,类B是一个单独的类,其中包含与类A中的虚拟方法同名的方法.我试图将类C中的所有内容捆绑在一起.继承C中的类B和A(多重继承),并使用类B中的方法实现类A中的方法.这种方式我创建了一种模块化方法.下面的示例是我的代码的非常简化的版本.

I am trying to do something I haven't really done before. I basically have 3 classes. Class A is an abstract class with pure virtual methods, Class B is a class on it's own that contains methods with the same name as the virtual methods in Class A. I'm trying to tie everything together in Class C. I'd like to inherit class B and A in C (multiple inheritance), and use the methods from Class B to implement those in class A. This way I create a modular approach. The example below is a very simplified version of my code.

class A {
virtual int methodA() = 0;
virtual int methodB() = 0;
virtual int methodC() = 0;
};

class B { //B implements A.A() and A.B()
int methodA() { return 0; }; 
int methodB() { return 0; };
};

class C : A, B {
int methodC() { return 0; }; //C implements A.C()
};

我可以编译C类,但是当我尝试构造C类时new C(),我收到一条编译器消息,提示由于以下成员,无法实例化抽象类:int methodA()':is abstract" .

I can compile class C but when I try construct a class of C new C() I get a compiler message saying "cannot instantiate abstract class due to following members: int methodA()' : is abstract".

是否存在通过类C中的多个继承使用类B实现类A的方法?

Is there a way to implement class A using class B through multiple inheritance in class C?

希望保持B类具体.

推荐答案

您可以使用某些方法的样板.

You can do it with some method-by-method boilerplate.

class A {
public:
virtual int methodA() = 0;
virtual int methodB() = 0;
virtual int methodC() = 0;
};

class B { //B implements A.A() and A.B()
public:
int methodA() { return 0; }; 
int methodB() { return 0; };
};

class C : public A, public B {
public:
int methodA() { return B::methodA(); }
int methodB() { return B::methodB(); }
int methodC() { return 0; }; //C implements A.C()
};

演示: http://ideone.com/XDKDW9

这篇关于从继承的类实现抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆