新年快乐!我对 C++ 及其社区都比较陌生,如有任何错误,我深表歉意。
我正在实现一个带有函数的mat
(矩阵)类,带有返回类型。我想实现一个具有相同功能的子类(方阵),但返回.mat static Zeros(const int rows, const int cols)
mat
sqmat
Zeros
sqmat
我来到了这个解决方案:
class mat{
private:
int rows;
int cols;
double* data;
public:
mat(int rows, int cols){
this -> rows = rows;
this -> cols = cols;
data = new double[rows*cols];
}
virtual ~mat(){ delete data; }
static mat Zeros(int rows, int cols){
mat matrix(rows, cols);
matrix.zero();
return matrix;
}
mat& zero(){
for(int i = 0; i < rows*cols; i++)
data[i] = 0;
return *this;
}
}
class sqmat : public mat {
public:
sqmat(int dim) : mat(dim){};
static sqmat Zeros(int dim){
sqmat matrix(dim);
matrix.zero();
return matrix;
}
}
换句话说,我使用了一个备份成员函数zero
来进行所有计算,而我使用了父类和子类中的静态函数来处理返回类型。这样可以避免代码重复,但感觉不对。
实际上,这需要为我想为父类和子类实现的每个静态函数创建一个备份成员函数,只返回适当的数据类型。有没有更有效的方法来处理这个问题?
不幸的是,在我的教科书和互联网上,多态性都是使用void
返回函数来解释的,所以我没有很多例子。
PS请避免使用模板或“高级”方法