使用相同方法但不同成员类型构建类的最佳方法
Best way to structure classes with identical methods but different member types
寻找有关如何改进以下代码以最大化重用的建议。 类 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_A
和Matrix_Type_B
具有相同的方法?如果它们都是声明共享功能的公共父级的子类(或者如果可以让它们像这样共享父级(,只需将matrix
变量声明为该父级类型即可。
如果没有,你可以创建一个模板类:
template<class Matrix>
class C
{
...
protected:
Matrix matrix;
...
}
并使用C<Matrix_Type_A>
或C<Matrix_Type_B>
作为您的课程。
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 将 OpenCV 与 CMAKE 中的项目一起构建为第三方库的正确方法
- 更改命令行 qt5 源代码构建配置的正确/快速方法
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 创建进行生产构建并创建调试信息的C++生成文件的最佳方法?
- 将vector<vector<double>>从x86平台中创建的一个进程发送到x64中构建的另一个进程的最快方法是什么
- 有没有一种方法可以在linux中扫描已构建的ARM库中的函数
- 使用相同方法但不同成员类型构建类的最佳方法
- 使用 openssl 构建静态二进制文件的正确方法是什么?
- 设置用G 构建的二进制版本的任何方法
- cpp 中是否存在一种数据结构,可以轻松地提供一种基于已存在的实例构建新结构的方法
- VS2013在构建容器应用程序时无法识别OCX控制的附加方法
- 是否有任何可能的方法将事件(自定义)附加到在运行时创建的对象?[C 构建器]
- 我们可以在 caa 的构建图方法中只使用初始状态和空状态吗?
- Linux/GCC:是否有一种方法可以检查构建是否与其他机器上的前一个机器相同
- 有什么方法可以为Emscripten构建Zeromq
- ifstream的已删除副本构建器的替代方法
- CMake 构建错误 - 虚拟方法错误缺少 vtable
- 构建数据库,读取方法
- 在Linux上构建具有链接时代码生成功能的静态库的正确方法是什么