C++ 操作符=的重载

可以把赋值操作符认为是一个析构函数和一个复制构造函数的组合

 

Spreadsheet& Spreadsheet::operator =(const Spreadsheet& rhs)
{
    int i, j;
    if (this == &rhs)   //判断赋值号两边是否相等
    {
        return (*this);
    }
    
    for (i = 0; i < mWidth; i++)  //首先释放旧的内存
    {
        delete[] mCells[i];
    }
    delete[] mCells;
    
    mWidth = src.mWidth;
    mHeight = src.mHeight;
    mCells = new SpreadsheetCell* [mWidth];
    for (i = 0; i < mWidth; i++)      //然后创建新的内存
    {
        mCells[i] = new SpreadsheetCell [mHeight];

    }
    for (i = 0; i < mWidth; i++)
    {
        for(j = 0; j < mHeight; j++)
        {
            mCells[i][j] = src.mCells[i][j];
        }
    }
}


 

你可能感兴趣的:(C++ 操作符=的重载)