使用相同方法但不同成员类型构建类的最佳方法

Best way to structure classes with identical methods but different member types

本文关键字:方法 构建 类型 最佳 成员类 成员      更新时间:2023-10-16

寻找有关如何改进以下代码以最大化重用的建议。 类 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();
}

如何确保Matrix_Type_AMatrix_Type_B具有相同的方法?如果它们都是声明共享功能的公共父级的子类(或者如果可以让它们像这样共享父级(,只需将matrix变量声明为该父级类型即可。

如果没有,你可以创建一个模板类:

template<class Matrix>
class C
{
...
protected:
Matrix matrix;
...
}

并使用C<Matrix_Type_A>C<Matrix_Type_B>作为您的课程。