不修改Matrix类,如何在类外获取私有二维向量的深度?
解决方案
核心思路:将
ostream& operator<<和istream& operator>>声明为Matrix类的友元函数,这样它们就能直接访问类的私有成员二维向量2d,通过2d.size()获取矩阵行数(深度),通过2d[0].size()获取列数(宽度)。具体操作示例:
在Matrix类定义中添加友元声明:class Matrix { private: vector<vector<int>> 2d; // 元素类型可根据实际情况调整 // 其他私有成员 public: // 已实现的成员函数 friend ostream& operator<<(ostream& os, const Matrix& mat); friend istream& operator>>(istream& is, Matrix& mat); };函数实现中直接访问私有成员:
ostream& operator<<(ostream& os, const Matrix& mat) { int rows = mat.2d.size(); if (rows == 0) { return os; } int cols = mat.2d[0].size(); // 遍历输出矩阵元素 for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { os << mat.2d[i][j] << " "; } os << endl; } return os; } istream& operator>>(istream& is, Matrix& mat) { mat.2d.clear(); int rows, cols; is >> rows >> cols; // 读取矩阵元素并填充 for (int i = 0; i < rows; ++i) { vector<int> row; for (int j = 0; j < cols; ++j) { int val; is >> val; row.push_back(val); } mat.2d.push_back(row); } return is; }注意事项:处理空矩阵时需先判断
2d.size()是否为0,避免访问2d[0]引发越界错误。
内容的提问来源于stack exchange,提问作者wonkas42
相关产品推荐
相关产品推荐

