c++ - 如何将二维矩阵传递给函数

标签 c++

我正在使用类添加矩阵。我已经声明了一个类“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/

相关文章:

c++ - 我可以将 std::variant<Ts...> 分配给/构造 std::variant<Ts..., Ys...> 吗?

c++ - __targv 在我的 MFC Windows 应用程序中为 NULL。参数== 1

c++ - 如何使用cpp的regex_iterator在第一次匹配时停止

c++ - 与非常量引用参数交换

c++ - 如何使用 C++ std::barrier arrival_token?

c++ - 使用带有仿函数结构的 libuv 而不是函数回调

c++ - 用别名替换默认模板参数

c++ - 在 C++ 中有效地使用继承

c++ - C++ API 的 REST 与 RPC

c++ - 将 std::shared_ptr 用于 std::vector 时发生内存泄漏