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