如果我想使用继承来避免重复下面的common_method
方法
int A::different_method()
{ return 1; }
int A::common_method()
{ return this->different_method()+1; }
int B::different_method()
{ return 2; }
int B::common_method()
{ return this->different_method()+1; }
什么是最好的方法?
一种方法是使用新方法使A
和B
从基类C
继承:
int A::different_method()
{ return 1; }
int B::different_method()
{ return 2; }
int C::different_method()
{ return 0; }
int C::common_method()
{ return this->different_method()+1; }
但是我也必须定义无用的C::different_method
有点令人讨厌。这种情况下的最佳做法是什么?
答案 0 :(得分:3)
答案 1 :(得分:2)
一种方法是使A和B从基类C继承,
是的,您需要一个基本的class C
class C {
public:
virtual ~C() { }
virtual int different_method() = 0;
virtual int C::common_method() {
return this->different_method()+1;
}
}
class A: public C {
// Implement
int different_method() override;
};
class B: public C {
int different_method() override;
};
答案 2 :(得分:1)
如果只需要使用类A和B,则可以将C类声明为抽象类,并仅实现common_method()
。可以通过以下方式在C类的头文件中将different_method()
声明为 纯虚函数 :
virtual different_method()=0
的有用链接
答案 3 :(得分:0)
您真的绑定A a; a.common_method()
语法吗?
为什么不
template <typename T>
int common_free_function(T& t) {
return t.different_method() + 1;
}
A a;
B b;
common_free_function(a);
common_free_function(b);