| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
共有 119 人关注过本帖
标题:matrix类实现的权限问题
只看楼主 加入收藏
学C的菜鸡
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2025-4-14
收藏
 问题点数:20 回复次数:1 
matrix类实现的权限问题
程序代码:
class matrix {
private:
    vector<vector<float>>data;
    int rows;
    int cols;
public:
    matrix(int _rows, int _cols) :rows(_rows), cols(_cols), data(rows, vector<float>(cols, 0.0f)) {}
    matrix(const vector<vector<float>>& input) :data(input), rows(input.size()), cols(input[0].size()) {}

    int getCols()const { return cols; }
    int getRows()const { return rows; }
    void setValue(int i, int j, float value) { data[i][j] = value; }
    float& operator()(int i, int j) { return data[i][j]; }
    const float& operator()(int i, int j)const { return data[i][j]; }

    vector<float> operator *(const vector<float>& vec) const {
        if (cols != vec.size()) {
            throw invalid_argument("Matrix and vector dimensions do not match!");
        }
        vector<float> result(rows, 0.0f);
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result[i] += data[i][j] * vec[j];
            }
        }
        return result;
    }
};
matrix mat(3,3);
mat(0,0) = 1.0f;
为什么我这样写通过mat(0,0)赋值会报错,通过setValue同样会报错,把data从private拿到public又不会报错了
3 天前 17:44
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9047
专家分:54175
注 册:2011-1-18
收藏
得分:0 
赋值会报错
你的“报错”指的是编译期语法报错,还是运行报错?话要讲清楚,起码编译是没错的!

错误的地方:
声明顺序是 data、rows、cols,所以初始化列表也依此顺序,即先执行 data(rows, vector<float>(cols, 0.0f)) 再执行 rows(_rows) 和 cols(_cols),也就是执行 data(rows, vector<float>(cols, 0.0f) 时 rows 和 cols 尚未赋值

糟糕的地方:
1. vector<vector<float>>data; 是个什么玩意儿?难道不应该是 vector<float> data 然后分配 rows*cols 个元素吗?
2. 用 size_t,不是 int

可改进的地方:
1. 必要的地方添加 noexcept
2. 如果你用的编译器不是很老旧的话,可以重载 operator[size_t,size_t],比 mat(0,0) 更自然一些
前天 08:33
快速回复:matrix类实现的权限问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.162718 second(s), 10 queries.
Copyright©2004-2025, BC-CN.NET, All Rights Reserved