返回继承静态函数的类型

时间:2017-01-01 23:24:04

标签: c++ inheritance matrix static static-polymorphism

新年快乐! 我对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避免使用模板或“高级”方法

0 个答案:

没有答案