gpt4 book ai didi

c++ - 为什么 operator[] 在初始化时有效,而在引用二维动态数组时无效

转载 作者:行者123 更新时间:2023-11-30 03:34:54 24 4
gpt4 key购买 nike

我无法理解标题中的问题。所以有我的两个类,一个 Vector of 3 doubles 和一个 2D 动态 Matrix,每个单元格都有一个 Vector 对象。Matrix 的构造函数工作并且不会抛出错误。但是,当我想在 ostream 重载中引用创建的 Matrix 实例的单元格时,我得到了

"no match for 'operator[]' (operand types are 'Matrix' and 'int')"

为什么在初始化期间使用 [][] 表示法可以,而之后就不行了?有没有一种适度直接的方法来解决这个问题?非常感谢!

class Vector{
private:
double x, y, z;

public:
Vector(){
x = y = z = 0;
}
Vector(int x_, int y_, int z_){
x = x_;
y = y_;
z = z_;
}
friend ostream &operator<< (ostream &wyj, Vector &v);
friend istream &operator>> (istream &wej, Vector &v);
};
/// ===== MATRIX CLASS CONSISTS OF VECTOR OBJECTS
class Matrix{
private:
Vector ** M;
int row;
int col;

public:
Matrix(int col, int row){
M = new Vector * [row];
for(int i = 0; i < row; i++){
M[i] = new Vector[col];
}
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
M[i][j] = Vector();
}
}
}

friend ostream &operator<< (ostream &wyj, Matrix &M);

};

ostream &operator<< (ostream &wyj, Matrix &M){

for(int i = 0; i < M.row; i++){
for(int j = 0; j < M.col; j++){
wyj << M[i][j] << " ";
}
wyj<< endl;
}
return wyj;
}

int main(){
Matrix A(2, 2);
cout << A[1][1]; // LURD VADAR SAYZ NOOOOOOOOOOOOOOO

}

编辑:<<重载方法中的小拼写错误

最佳答案

Why is it OK to use the [][] notation during initialization and not OK later?

Matrix 的构造函数M 中是一个Vector**。在 main() 中,A 是一个 Matrix。所以 [][] 对于 Vector** 是可以的,但对于 Matrix 没有意义(除非定义)。

Is there a moderately straightforward way to fix this?

要使 [][] 正常工作,您需要定义两次 operator[]。一次用于第一个对象,一次用于第一个 operator[] 返回的对象。

所以在 Matrix 中你可以包括:

Vector* operator[](size_t index) { return M[index]; }

关于c++ - 为什么 operator[] 在初始化时有效,而在引用二维动态数组时无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41655813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com