【发布时间】:2015-02-18 21:31:07
【问题描述】:
我正在尝试重载 () 运算符以将值分配给动态分配的二维数组,这是我的代码 --
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类型语句的正确构造应该是什么?
【问题讨论】:
标签: c++ c++11 operator-overloading dynamic-memory-allocation