C++中的效率和赋值运算符重载

Efficent Sum and Assignment operator overloading in C++

本文关键字:赋值运算符 重载 效率 C++      更新时间:2023-10-16

嗨,我正在用 c++
实现一个矩阵类我知道有一些很棒的库可以像opencv一样做到这一点,但我需要自己做。

例如,如果我实现总和,我可以像这样做

class Mat{
public:
    double* data;
    int rows,cols;
    Mat(int r,int c):rows(r),cols(c){
        data = new double[r*c];
    }
};
void Sum(Mat& A,Mat& B,Mat& C){
    for (int i = 0; i < A.rows*A.cols; ++i){
        C.data[i] = A.data[i]+B.data[i];
    }   
}
int main(){    
    //Allocate Matrices
    Mat A(300,300);
    Mat B(300,300);
    Mat C(300,300);
    //do the sum
    sum(A,B,C);
}

我想得到这样更具可读性的东西,但又不损失效率

C = A + B

这样 C 每次都会重新分配,我不希望这样

谢谢你的时间

延迟计算。

class MatAccess {
    friend class Mat;
    friend class MatOpAdd;
    virtual double operator[](int index) const = 0;
};
class MatOpAdd: public MatAccess {
friend class Mat;
private:
    const MatAccess& left;
    const MatAccess& right;
    MatOpAdd(const MatAccess& left, const MatAccess& right):
        left(left), right(right) {}
    double operator[](int index) const {
        return left[index] + right[index];
    }
};
class Mat: public MatAccess{
public:
    double* data;
    int rows,cols;
    Mat(int r,int c):rows(r),cols(c){
        data = new double[r*c];
    }
    MatOpAdd operator +(const MatAccess& other) {
        return MatOpAdd(*this, other);
    }
    const Mat& operator = (const MatAccess& other) {
        for(int i = 0; i < rows*cols; ++i) {
            data[i] = other[i];
        }
        return *this;
    }
private:
    double operator[](int index) const {
        return data[index];
    }
    double& operator[](int index) {
        return data[index];
    }
};

int main(){    
    //Allocate Matrices
    Mat A(300,300);
    Mat B(300,300);
    Mat C(300,300);
    //do the sum
    C = A + B;
}

现在,"+"计算将在"运算符="中完成

我会改变的事情:

  • MatAccess应包括维度(行,列)。
  • Mat添加构造函数和operator=或使其不可复制
  • Mat::operator+Mat::operator=检查相等的行,列
  • 不再使用时删除内存或
  • 使用std::vector简化内存管理。

在这里创建了一个更大的例子:https://gist.github.com/KoKuToru/1d23af4bbf0b2bc89893