我正在使用类添加矩阵。我已经声明了一个类“Matrix”。现在我需要将 Matrix 的对象传递给函数。我该怎么做?
最佳答案
实际上,最好的方法(恕我直言)是重载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++ 来说不是可取的。
关于c++ - 如何将二维矩阵传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13606482/