---
title: "条款15: 让operator=返回*this的引用"
author: "lin_style"
date: "2008-02-02T21:59:09Z"
tags: []
categories: ["编程语言"]
slug: "15-operator-this"
draft: false
lastmod: "2008-02-02T21:59:09Z"
id: 161244
url: "https://lin-style.iteye.com/blog/161244"
---

条款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的临时对象

最大的争论是对函数的返回值

```java
string& string::operator=(const string& rhs)
{
  ...
  return *this;            // 返回左边的对象
}

string& string::operator=(const string& rhs)
{
  ...
  return rhs;              // 返回右边的对象
}
```


如果单从效果来讲，两者是一样的。从语法来看return rhs是通不过的，如果改成string& rhs,那么对临时对象又无可奈何