随笔-348  评论-598  文章-0  trackbacks-0
1.今天看到了Mastering Classes and Objects这章,发现Copy Constructor还是自己写好,作者已经用很详细的例子说明了Compiler为我们构造的Copy Constructor,只是将变量指向那块已分配的内存,而不是真正的Copy...所以我们需要重新构造自己的 Constructor将被Copy的变量真正的Copy过来,用两个内存空间存放同样的数据。

operator=也是一样,我们应该先将原变量内部的一些内存空间释放掉,然后申请新的来存放=右边的内部成员。
 1Spreadsheet::Spreadsheet(const Spreadsheet& src)
 2{
 3int i, j;
 4mWidth = src.mWidth;
 5mHeight = src.mHeight;
 6mCells = new SpreadsheetCell* [mWidth];
 7for (i = 0; i < mWidth; i++{
 8mCells[i] = new SpreadsheetCell[mHeight];
 9}

10for (i = 0; i < mWidth; i++{
11for (j = 0; j < mHeight; j++{
12mCells[i][j] = src.mCells[i][j];
13}

14}

15}

Spreadsheet& Spreadsheet::operator=(const Spreadsheet& rhs)
{
int i, j;
// Check for self-assignment.
if (this == &rhs) {
return (*this);
}

// Free the old memory.
for (i = 0; i < mWidth; i++{
delete[] mCells[i];
}

delete[] mCells;
// Copy the new memory.
mWidth = rhs.mWidth;
mHeight 
= rhs.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] 
= rhs.mCells[i][j];
}

}

2.区分下
SomeClass sc;
SomeClass scAnother;
scAnother
=sc;


SomeClass sc;
SomeClass scAnother
=sc;

其实两个的意思是不一样的,前者调用的是operator=而后者调用的是Copy Constructor。
如果你没有重载operator=,那么两段代码都是重载Copy Constructor.

发现写写笔记,还是有助于记忆的。

---------------------------------------------------------
专注移动开发

Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian
posted on 2007-01-31 13:27 TiGERTiAN 阅读(385) 评论(0)  编辑  收藏 所属分类: C/C++

只有注册用户登录后才能发表评论。


网站导航: