c++ - 成员仅因类型不同而不同的 C++ 类

标签 c++ inheritance polymorphism

这可能是一个非常简单的问题,但我不确定要搜索什么才能找到解决方案。我有如下所示的三个类:

class class_double_array {
public:
    double *value;
    int height;
    int width;

    void alloc(const int &h, const int &w);
}


class class_int_array {
public:
    int *value;
    int height;
    int width;

    void alloc(const int &h, const int &w);
}


class class_logical_array {
public:
    bool *value;
    int height;
    int width;

    void alloc(const int &h, const int &w);
}

alloc 是:

void class_double_array::alloc(const int &h, const int &w) {
    width = w;
    height = h;
    value = (double*)calloc(h*w,sizeof(double));
}

在 C++ 中是否有组织这些类的标准方法?这是一个非常简化的示例,但我有一些类似的东西,其中类方法基本相同但取决于 value 的类型。在这个例子中,我必须为每个类重写 alloc,即使它基本上为每个类做同样的事情。我一直在研究使用模板,但找不到我要找的东西。

最佳答案

像这样:

template<typename T>
class T_array
{
public:
    T *value;
    int width;
    int height;

    void alloc(const int &h, const int &w)
    {
        width = w;
        height = h;
        value = (T*)calloc(h*w, sizeof(T));
    }
}

关于c++ - 成员仅因类型不同而不同的 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23876838/

相关文章:

c++ - mfc图片控件多次运行后消失

java - 如何判断一个Class是否继承于另一个Class?

java - 意外输出 "this.getClass().getSuperclass()"

没有 RTTI 的 C++ 双重分派(dispatch) "extensible"

c++ - 纯虚拟 friend 类

xml - 如何使用属性值作为 XML 多态类型选择的鉴别器?

c++ - Matlab 和 C++ 之间的转换

python - 在 C++ 中索引 tensorflow 输出张量

c++ - 静态全局变量的奇怪行为

TypeScript、泛型和instanceof