zoukankan      html  css  js  c++  java
  • 赋值运算符的重载

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

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

    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

  • 相关阅读:
    常用性能测试工具和命令汇总
    delphi try except语句 和 try finally语句用法以及区别
    delphi中 ExecSQL 与 open
    Javascript闭包
    遍历一个List的几种方法
    IDEA导入项目jar包红线、依赖问题....
    HashMap、Hashtable、ConcurrentHashMap的原理与区别
    记一次CPU飙升BUG
    创建单链表
    【剑指offer】题目二
  • 原文地址:https://www.cnblogs.com/helloforworld/p/5655203.html
Copyright © 2011-2022 走看看