条款15: 让operator=返回*this的引用

条款15: 让operator=返回*this的引用
这里的描述不想太多
标准格式是
string& operator=(const string& rhs);

尝试下const string& operator=(const string& rhs);
如果是 int i1, i2, i3;
(i1=i2)=i3; //i3给i1出错

string& operator=(string& rhs);
对普通的类型可以,但是如果是常数呢?
x = "hello";
这里的hello必须是个const的临时对象

最大的争论是对函数的返回值
string& string::operator=(const string& rhs)
{
...
return *this; // 返回左边的对象
}

string& string::operator=(const string& rhs)
{
...
return rhs; // 返回右边的对象
}


如果单从效果来讲,两者是一样的。从语法来看return rhs是通不过的,如果改成string& rhs,那么对临时对象又无可奈何
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
填充下面这个程序中所有出现// TODO: fill the code这个任务的地方#include <iostream> #include <cstring> #include "ourstring.h" #include "strlib.h" using namespace std; OurString::OurString(){ // TODO: fill the code } OurString::OurString(const char *str){ // TODO: fill the code } OurString::OurString(const OurString &dstr){ // TODO: fill the code } OurString::~OurString(){ // TODO: fill the code } string OurString::toString() const{ // TODO: fill the code } OurString OurString::subStr(unsigned int start, unsigned int n) const{ // TODO: fill the code } bool OurString::operator > (const OurString &dstr) const{ // TODO: fill the code } bool OurString::operator < (const OurString &dstr) const{ // TODO: fill the code } bool OurString::operator == (const OurString &dstr) const{ // TODO: fill the code } unsigned int OurString::length () const{ // TODO: fill the code } const OurString& OurString::operator = (const OurString &dstr){ // TODO: fill the code } const OurString& OurString::operator = (const char *str){ // TODO: fill the code } char& OurString::operator[](int index){ // TODO: fill the code } const OurString OurString::operator + (const OurString &dstr) const{ // TODO: fill the code } const OurString OurString::operator + (const char *str) const{ // TODO: fill the code } const OurString& OurString::operator += (const OurString &dstr){ // TODO: fill the code } const OurString& OurString::operator += (const char *str){ // TODO: fill the code } ostream & operator<<(ostream &os, const OurString &dstr){ // TODO: fill the code } istream & operator>>(istream &is, OurString &dstr){ // TODO: fill the code }
05-29

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值