C++重载<<运算符打印静态矩阵,如何在main函数调用该运算符输出
实现方法
你重载的<<运算符仅支持Matrix类对象的输出,不能直接传入原生二维数组,只需在main函数中创建Matrix实例,将数组A的数值赋值给实例的成员数组后即可调用重载运算符打印,完整可运行代码如下:
#include <iostream> class Matrix { public: int matrix[3][3]; friend std::ostream& operator<<(std::ostream& out, const Matrix& e); }; std::ostream& operator<<(std::ostream& out, const Matrix& e) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { out << e.matrix[i][j] << " "; } out << std::endl; } out << std::endl; return out; } int main() { int A[3][3] = { {1,1,1},{1,0,0},{0,0,1} }; // 创建Matrix实例 Matrix mat; // 拷贝数组数值到Matrix成员 for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ mat.matrix[i][j] = A[i][j]; } } // 调用重载的<<运算符打印 std::cout << mat; return 0; }
可选优化:添加构造函数简化调用
可以给Matrix类添加接收二维数组的构造函数,省去手动拷贝数组的步骤:
class Matrix { public: int matrix[3][3]; // 新增构造函数 Matrix(const int arr[3][3]){ for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ matrix[i][j] = arr[i][j]; } } } friend std::ostream& operator<<(std::ostream& out, const Matrix& e); };
此时main函数可以直接简化为:
int main() { int A[3][3] = { {1,1,1},{1,0,0},{0,0,1} }; std::cout << Matrix(A); return 0; }
内容的提问来源于stack exchange,提问作者alex
相关产品推荐
相关产品推荐

