我遇到了为下面的类编写重载赋值运算符的问题:
namespace w3{
class DArray2d{
int rows;
int columns;
double **array;
public:
DArray2d();
DArray2d(int, int);
DArray2d(const DArray2d &obj);
DArray2d& operator=(DArray2d& rhs);
DArray2d(const DArray2d &&obj);
DArray2d& operator=(DArray2d&& rhs);
double check() const;
~DArray2d();
};
}
这是我尝试过的,但是我遇到了分段错误:11当我尝试复制for循环中的每个元素时:
w3::DArray2d& w3::DArray2d::operator=(w3::DArray2d& rhs){
// std::cout << "assignment operator" << std::endl;
if ( this != &rhs )
{
this->rows = rhs.rows;
this->columns = rhs.columns;
std::cout << this->rows << std::endl;
std::cout << this->columns << std::endl;
for(int a = 0; a < rhs.rows; a++){
for(int b = 0; b < rhs.columns; b++){
array[a][b] = rhs.array[a][b];
}
}
}
return *this;
}
我有一个复制构造函数,我可以使用它吗?
w3::DArray2d::DArray2d( const DArray2d &obj):rows(obj.rows), columns (obj.columns) {
// std::cout << "copy constructor" << std::endl;
if(this != &obj){
array = new double*[obj.rows];
for(int i = 0; i < obj.columns; i++){
array[i] = new double[columns];
}
for(int a = 0; a < obj.rows; a++){
for(int b = 0; b < obj.columns; b++){
array[a][b] = obj.array[a][b];
}
}
}
}
另外,这是删除二维数组的正确方法吗?
for (int a = 0; a < rows ; ++a){
delete [] array[a];
}
delete [] array;