条款10:operator = 返回一个reference to *this
看一个链式赋值语句
string x, y, z;
x = y = z = "My string";</span>
内部的实现是这样的
x.operator = (y.operator = (z.operator = ("My string")));</span>
我们自己来写一个string类的赋值函数
mystring.h
class Mystring
{
public:
Mystring();
~Mystring();
Mystring(const char *str);
Mystring(const Mystring & mystring);
Mystring operator = (const Mystring &mystring);
Mystring & operator +=(const Mystring &mystring);
Mystring operator + (const Mystring &mytring);
Mystring substr(const size_t pos, const size_t size);
size_t length() const;
friend ostream& operator << (ostream &out, const Mystring &string);
private:
int m_len;
char *m_value;
};
mystring.cpp
<span style="font-family:SimSun;font-size:18px;">#include "mystring.h"
Mystring::Mystring()
{
m_value = new char[1];
*m_value = '\0';
m_len = 0;
}
Mystring::~Mystring()
{
if (m_value != NULL)
delete m_value;
m_value = NULL;
}
Mystring::Mystring(const char* str)
{
if (str == NULL) {
m_value = new char[1];
*m_value = '\0';
m_len = 0;
} else {
m_len = strlen(str);
m_value = new char[m_len + 1];
strcpy(m_value, str);
}
}
Mystring::Mystring(const Mystring &mystring)
{
this->m_len = strlen(mystring.m_value);
this->m_value = new char[m_len + 1];
strcpy(this->m_value, mystring.m_value);
}
size_t Mystring::length() const
{
return m_len;
}
Mystring & Mystring::operator = (const Mystring &mystring)
{
if (this != &mystring) {
delete this->m_value;
this->m_len = mystring.length();
this->m_value = new char[m_len + 1];
strcpy(this->m_value, mystring.m_value);
}
return *this;
}
Mystring Mystring::operator + (const Mystring &mystring)
{
Mystring temp;
temp.m_value = new char[this->length() + mystring.length() + 1];
strcpy(temp.m_value, this->m_value);
strcat(temp.m_value, mystring.m_value);
return temp;
}
Mystring & Mystring::operator +=(const Mystring &mystring)
{
Mystring temp = *this;
delete []this->m_value;
this->m_value = new char[this->m_len + mystring.m_len + 1];
strcpy(this->m_value, temp.m_value);
strcat(this->m_value, mystring.m_value);
return *this;
}
Mystring Mystring::substr(const size_t pos, const size_t size)
{
Mystring temp;
if (pos > m_len) {
return temp;
}
char *p = this->m_value + pos;
temp.m_value = new char[size + 1];
strncpy(temp.m_value, p, size);
*(temp.m_value + size) = '\0';
return temp;
}
ostream& operator << (ostream &out, const Mystring &mystring)
{
out<<mystring.m_value;
return out;
}</span>
该篇讨论拷贝赋值函数=,为什么需要返回引用??
便于使用链式赋值
其实如果返回void型程序也是通过,但是不能实现x = y = z这种链式赋值
提高程序效率
为什么要返回引用呢,返回值不也可以达到这种效果啊。return value的确可以实现链式赋值,而且结果是一样的。但是如果返回值程序执行是这样的:返回对象先调用拷贝构造函数初始化一个编译器生成的临时变量,返回后,又调用析构函数析构临时对象,加入一个类中含有很多这样的成员,这是一个很大的开销,而返回引用可以避免这些开销。
记住
令赋值(assignment)操作符返回一个reference to *this