2012-11-28 52 views

回答

0

你有很多方法可以做到這一點。

按值:

void func (Matrix m); 

通過參考:

void func (Matrix& m); 

或指針:

void func (Matrix* m); 

使用哪種方法取決於你的需求和操作的語義。

+0

非常感謝! – User14229754

1

其實,最好的方法(恕我直言)是超載operator+()。因此,在你的代碼,你只需要+使用:

class Matrix { 
    private: 
     // Your code 
    public: 
     // Your code 
     friend Matrix operator+(const Matrix &c1, const Matrix &c2); 
} 

friend Matrix operator+(const Matrix &c1, const Matrix &c2) { <--- passing by reference 
    // Your code to add matrices 
} 

int main() { 
    Matrix A, B; 
    Matrix C = A + B; 
} 

在傳球的情況下,通過價值Matrix sum(Matrix a, Matrix b),則需要如果矩陣內存動態分配給寫一個拷貝構造函數。

通過指針傳遞Matrix sum(Matrix *a, Matrix *b)是一種C風格的編碼,所以它仍然是正確的,但不是C++的優選。