赋值运算符的重载

赋值运算符两边的类型可以不匹配,需要重载赋值运算符‘=’。赋值运算符只能重载为成员函数

重载赋值运算符的意义----浅复制和深复制

S1=S2;

浅复制/浅拷贝

  • 执行逐个字节的复制工作

深复制/深拷贝

  • 将一个对象中指针变量指向的内容复制到另一个对象中指针成员对象指向的地方

对operator=返回值类型的讨论。

void不可以,例如a=b=c;

运算符重载时,好的风格 ---尽量保留运算符原本的特性

例如(a=b)=c;//会修改相应a的值,因此使用String &更为合理。

#include <iostream>
#include <cstring>
using namespace std;

class String
{
private :
    char * str;
public:
    String() :str(NULL) 
    {
        cout << "the constructor is called " << endl;
    }
    const char * c_str()
    {
        return str;
    }
    char * operator =(const char *s);
    String & operator=(const String & s);
    ~String();
};
String::~String()
{
    if (str)
    {
        delete []str;
    }
    cout << "the destructor is called " << endl;
}
char * String::operator=(const char *s)
{
    if (str)
    {
        delete []str;
    }
    if (s)
    {
        str = new char[strlen(s) + 1];
        strcpy_s(str,strlen(s)+1, s);
    }
    else
    {
        str = NULL;
    }
    return (str);
}
String & String::operator=(const String &s)
{
    if (str == s.str) return (*this);
    if (str)
    delete[] str;
    str = new char[strlen(s.str) + 1];
    strcpy_s(str, strlen(s.str) + 1, s.str);
    return (*this);
}
int main()
{
    //String s2="Hello"//出错,因为这是初始化语句,不是赋值。
    String s1,s2,s3;
    s1 = "Hello world";
    s2 = "that";
    s3 = "this";
    //s1 = s2;//浅复制出错,两个指针指向同一空间,对象释放时会调用两次出错。
    s1 = s2;
    cout << s1.c_str() << endl;
    cout << s2.c_str() << endl;
    return 0;
}

 参考链接:

https://www.coursera.org/learn/cpp-chengxu-sheji

原文地址:https://www.cnblogs.com/helloforworld/p/5655203.html