You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:20:20