Implement abstract methods from inherited class

旧巷老猫 提交于 2019-12-10 10:47:49

问题


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()
};

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".

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

Edit: The wish is to keep class B concrete.


回答1:


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()
};

Demo: http://ideone.com/XDKDW9



来源:https://stackoverflow.com/questions/18389532/implement-abstract-methods-from-inherited-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!