• 赋值运算符函


    1. 赋值运算符的重载函数的声明,需要返回类型的引用,也就是CMyString& ,这里是为了考虑到形如 a = b = c这样的连续赋值操作,因此需要在函数结束前加上return *this;
    2. 函数传参需要引用,这样避免了调用一次拷贝构造函数提高效率,同时为了不改变传入实例,需要加上const
    3. 重新分配内存时候,必须要释放之前自己已有的空间,否则会导致内存泄漏
    4. 要考虑到自己赋值给自己,即this == &other时候,其实不需要执行任何操作,同时更为重要的是:对于我自己写的代码如果不加上if (this != &other)代码就是错的,因为我是先释放内存再根据other需要的空间开辟一块新空间,对于自己赋值给自己的情况,由于已经自己指向的那块空间已经释放了,所以再也找不到需要赋值的内容了。

    #include <iostream>
    #include <cstring> 
    using namespace std;
    
    class String
    {
        public:
            String(const char *s=nullptr);//自定义构造函数 
            String(const String &s1);//拷贝构造哈数 
            String &operator=(const String &s);//赋值构造函数 
            void print();
        private:
            char *data;
    };
    
    String::String(const char *s)
    {
        if(s==NULL)
        {
            data=new char[1];
            data[0]='';
        }
        else
        {
            data=new char[strlen(s)+1];
            strcpy(data,s);
        }
    }
    
    String::String(const String &s1)
    {    
        data=new char[strlen(s1.data)+1];
        strcpy(data,s1.data);
        //cout<<" copy."<<endl;
    }
    
    String &String::operator=(const String &s)
    {
        if(&s==this)//防止自己赋值 
            return *this;
        
        delete []data;
        data=new char[strlen(s.data)+1];
        strcpy(data,s.data);
        //cout<<" operator=."<<endl;
    }
    
    void String::print() 
    {
        cout<<data<<endl;
    }
    
    int main()
    {
        String s("hello word.");//自定义构造函数 
        String s2=s;//拷贝构造函数 
        String s3(s2);//s3需要用s2初始化,调用拷贝构造函数 
        s2=s3;//s2,s3已存在。调用赋值构造函数 ;当一个类的对象向该类的另一个对象赋值时,就会用到该类的赋值函数。首先该对象要存在 
        s2.print();
        s3.print();
        return 0;
    }
  • 相关阅读:
    JAVA调用WebService总结
    关于购物车的想法
    ASP.NET中初试Ajax
    转帖:从FxCop归纳出来的一些规范建议
    数据结构(二叉树)C#描述
    FormView控件和DetailsGridView控件实现MasterSlave
    在.NET中使用MySql数据库
    Oracle学习总结1
    Oracle学习总结2
    关于字符匹配所引起的的问题
  • 原文地址:https://www.cnblogs.com/tianzeng/p/10072305.html
Copyright © 2020-2023  润新知