抽象类 IB 继承抽象类 IA 的接口,实现类 CB 继承自 IB,利用 template 给 CB 附加 IA 中虚函数的实现,CB 类的代码中只需添加 IB 中的虚函数的实现。
class IA {
virtual int f1() = 0;
};
class IB : public IA {
virtual int f2() = 0;
};
template <typename Interface>
class CA2 : public Interface {
int f1() {
printf("CA2::f1()\n");
return 1;
}
};
class CB : public CA2<IB> {
int f2() {
printf("CB::f2()\n");
return 2;
}
};
void test9() {
IA* pa = new CA2<IA>;
IB* pb = new CB;
}