注册 登录
编程论坛 C++教室

matrix类实现的权限问题

学C的菜鸡 发布于 2025-04-14 17:44, 543 次点击
程序代码:
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又不会报错了
1 回复
#2
rjsp2025-04-15 08:33
赋值会报错
你的“报错”指的是编译期语法报错,还是运行报错?话要讲清楚,起码编译是没错的!

错误的地方:
声明顺序是 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) 更自然一些
1