设为首页 加入收藏

TOP

effectiveC++(十七)(二)
2010-12-26 23:20:34 来源: 作者: 【 】 浏览:4352
Tags:effectiveC 十七
bsp;     //

  ~string();                    // 函数定义参见条款11
                                //
  ...

  string& operator=(const string& rhs);

private:
  char *data;
};

// 忽略了给自己赋值的情况
// 的赋值运算符
string& string::operator=(const string& rhs)
{
  delete [] data;    // delete old memory

  // 分配新内存,将rhs的值拷贝给它
  data = new char[strlen(rhs.data) + 1];
  strcpy(data, rhs.data);

  return *this;      // see item 15
}

看看下面这种情况将会发生什么:

string a = "hello";

a = a;               // same as a.operator=(a)

赋值运算符内部,*this和rhs好象是不同的对象,但在现在这种情况下它们却恰巧

是同一个对象的不同名字。可以这样来表示这种情况:

*this  data ------------>

首页 上一页 1 2 3 4 5 6 下一页 尾页 2/6/6
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇effectiveC++(十八) 下一篇effectiveC++(十六)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: