2
寻找有关如何改进下面的代码以最大限度地重复使用的一些建议。 A类有一个矩阵成员,用于几种方法。 B类与A类相同(这些方法是直接复制粘贴),但是矩阵成员不同且类型不同。使用完全相同的方法构建类但使用不同成员类型的最佳方法
class A
{
public:
A() { set_matrix(); };
double operator()() { // uses method1 and method2 };
protected:
Matrix_Type_A matrix;
void set_matrix();
double method1() { // uses matrix };
double method2() { // uses matrix };
}
class B
{
public:
B() { set_matrix(); };
double operator()() { // uses method1 and method2 };
protected:
Matrix_Type_B matrix;
void set_matrix();
double method1() { // uses matrix. Identical to method1 in class A };
double method2() { // uses matrix. Identical to method2 in class A };
}
理想情况下,我想重新使用类方法,其中底层代码适用于两种矩阵类型。
我最初的想法是创建一个具有新成员矩阵一个子类,但我不认为这会工作,因为继承的方法仍然指向基类的变量,而不是衍生变量。例如。是这样的:
class A
{
public:
A() { set_matrix(); };
protected:
Matrix_Type_A matrix;
void set_matrix();
double method1() { // uses matrix };
double method2() { // uses matrix };
}
class B : class A
{
private:
Matrix_Type_B matrix;
void set_matrix();
}
可替换地,在想,我可以用含有该方法的一般基类,然后继承类A和B类的每个与不同的矩阵构件。问题是,基类不会编译,因为这些方法引用只存在于派生类中的成员。
任何意见/想法如何构建这非常赞赏。
编辑:
模板解决方案似乎工作。我已经实现了以下
template <class T> class A
{
public:
A() { set_matrix(); };
protected:
T matrix;
virtual void set_matrix() = 0;
double method1() { // uses matrix };
double method2() { // uses matrix };
}
class B : class A<Matrix_Type_A>
{
public:
B() { set_matrix(); };
private:
void set_matrix();
};
class C : class A<Matrix_Type_B>
{
public:
C() { set_matrix(); };
private:
void set_matrix();
}
这听起来像一个模板类。 –
避免在构造函数中调用虚方法,您可以使用专用而不是继承,然后使用别名:'使用B = A;'。 –
Jarod42