【发布时间】:2019-06-27 13:59:02
【问题描述】:
假设我有一个接口类和一个部分实现类。另外,假设我绝对不希望这个部分实现从接口继承:
class interface {
virtual void fnA() const = 0;
virtual void fnB() const = 0;
};
class partialImplementation { //Do not want to inherit from interface!
void fnA() const {cout << "fnA from partial implementation" << endl;}
//fnB() not implemented
};
我的想法是我打算创建几个新类都继承接口,但我想在每个类中实现相同的fnA()。所以,在继承了接口之后,也许我也可以继承部分实现,希望fnA()能够实现。例如,
class myClass : interface, partialImplementation {
//would like fnA() to be implemented by partialImplementation
void fnB() const {cout << "fnB from myClass" << endl;}
};
当然,如果你尝试实例化这个类,你会得到这个错误:
main.cpp: In function 'int main()':
main.cpp:235:10: error: cannot declare variable 'm' to be of abstract type 'myClass'
main.cpp:201:7: note: because the following virtual functions are pure within 'myClass':
main.cpp:193:15: note: virtual void interface::fnA() const
Compilation failed.
在阅读了其他一些 stackoverflow 帖子(如 this one)之后,似乎唯一可用的解决方案是这样做:
class myClass : interface, partialImplementation {
public:
void fnB() const {cout << "fnB from myClass" << endl;}
void fnA() const {
partialImplementation::fnA();
}
};
在链接的帖子中,OP 不介意多输入三行。但您可以想象,我实际上希望 partialImplementation 实现不止一个功能,并且每次我想要创建一个继承此接口的新类时,我都可以一遍又一遍地键入相同的样板。
有谁知道不需要partialImplementation 继承自interface 的方法?
【问题讨论】:
-
这是最简单、最明显的方法。它的明确。这样更好。
-
是的,
partialImplementation继承自interface有什么问题? -
顺便说一句,如果您不继承,您可能看不到界面发生了变化,并且您的“部分”界面需要发展。最后,您似乎正在尝试实现 sme 类型的适配器,而无需付出适应的代价
-
如果
partialImplementation中的函数必须与interface中的函数相同,则partialImplementation应继承interface。这就是继承的意义。
标签: c++ inheritance abstract-class multiple-inheritance