c++中赋值运算符重载

c++编译器至少给一个类添加4个函数
1. 默认构造函数(无参,函数体为空)
2. 默认析构函数(无参,函数体为空)
3. 默认拷贝构造函数,对属性进行值拷贝
4. 赋值运算符 operator=, 对属性进行值拷贝

这个重载主要是为了防止有堆区的时候会有重复删除地址的问题,所以要有重载函数,进行深拷贝

跟拷贝构造函数的时候差不多,多出来的一点就是提前看一看时候有属性在堆区,如果没有再重新开辟

    A& operator=(const A& another)
    {
        this->len = new int(*another.len);
        this->name = another.name;
        return *this;      
    }
 
返回栈对象的引用,多用于产生串联应用。比如连等式。 栈对象是不可以返回引用的。除非,函数的调用者返回自身对象。
MyString & MyString::operator=(const MyString & another)
{
return *this;
}
MyString & MyString::operator=(const MyString & another)
{
return another;//不可行,因为another会在返回通过=表达式后析构,因此在这之后调用t的命令都找不到确定结果
}
MyString  t = b;
posted @ 2022-04-10 12:03  纸包鱼  阅读(69)  评论(0)    收藏  举报