2015-01-02 73 views
0

您好我在C++中實現了一個矩陣類
我知道有很多類似opencv的庫,但我需要自己做。在C++中的有效總和和賦值運算符重載

例如,如果我實現我可以這樣做

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被重新分配,每時間,我不想那

謝謝你的時間

+2

如果您使用C++ 11,看看http://stackoverflow.com/questions/3106110/what-is-move-semantics – NPE

+0

你確定'C = A + B;'相當於'sum(A,B,C);'。它不應該看起來像'Sum = A + B + C'嗎? –

+0

是的,它們是等價的我執行sum函數來總結前兩個矩陣並將結果保存在第三個 – Rosh

回答

1

延遲計算。

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應包括維度(行,COLS)。當不再或簡單的內存管理
  • 使用std::vector使用
  • Mat加入建設者和operator=或使其不可拷貝
  • Mat::operator+Mat::operator=支票等於行,列
  • 刪除記憶。

在這裏創造一個更大的例子:https://gist.github.com/KoKuToru/1d23af4bbf0b2bc89893

+0

哇我們在幾乎同一時間想出了類似的答案:)我是S0新手,在這種情況下該怎麼辦? – Rosh

+1

有兩種可能的解決方案,接受我的答案或張貼您自己的答案並接受您自己的答案。 不要在你的問題中發佈你的回答.. – KoKuToru

+0

好的非常感謝你:) – Rosh