我正在尝试重载 () 运算符以将值赋值到动态分配的二维数组中,这是我的代码 --
class test {
private:
int** data ; int row, col ;
public:
test(int row = 2, int col = 2) {
this->row = row ; this->col = col ;
this->data = new int*[this->row] ;
for(int i = 0 ; i < this->row ; i++)
this->data[i] = new int[this->col] ;
}
~test() {
for(int i = 0 ; i < this->row ; i++)
delete [] this->data[i] ;
delete [] this->data ;
}
const int operator() (int row, int col) { // read operation
return this->data[row][col] ;
}
int& operator() (int row, int col) { // write operation
return this->data[row][col] ;
}
// for printing
friend ostream& operator<< (ostream &os, const test &t);
};
在 operator() 写操作中,我试图通过引用返回值,以便我可以像这样赋值 --
test t(4,4) ;
t(2,2) = 5 ;
但它不编译,说我不能做这种重载,那么可以用来实现 t(2,2) = 5
类型的正确构造应该是什么的声明?
最佳答案
您的第一个重载必须采用以下形式:
int operator() (int row, int col) const
不是
const int operator() (int row, int col)
而且不是读操作,当你类型的对象被创建为const
时使用,会使用这个重载,如果不是const
,其他将使用重载,用于读取和写入。
关于c++ 重载 operator() 用于在动态二维数组中赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27574639/