c++中赋值运算符重载为什么要用引用做返回值?

 

class string{

public:

string(const char *str=NULL);

string(const string& str);     //copy构造函数的参数为什么是引用呢?  我相信大家都懂的!

string& operator=(const string & str); //赋值函数为什么返回值是引用呢?

~string();

};

如果返回值时, return *this后马上就调用拷贝构造函数。


但是万一由于没有定义拷贝构造函数  ,就会调用默认的拷贝构造函数。
我们知道调用默认的拷贝构造函数时当在类中有指针时就会出错(浅拷贝)。


所以如果你不用引用做返回时      就必须定义自定义的拷贝构造函数。

 

 

当然咯  有指针成员时 必须要注意    自定义  拷贝构造了

 

其实还是为了提高效率 和 减少零时对象的生成   不调用 拷贝构造函数!

 

 

 

 

 

class MyClass {
public:
    // 赋值运算符重载
    MyClass& operator=(const MyClass& other) {
        if (this != &other) {  // 自赋值检查
            // 执行赋值操作
            // ...
        }
        return *this;  // 返回对当前对象的引用
    }
};

int main() {
    MyClass a, b, c;
    a = b = c;  // 连续赋值
    (a = b).someMethod();  // 链式操作
    return 0;
}

在这个例子中,赋值运算符返回 *this 的引用,允许连续赋值和链式操作。它还提供了良好的效率和与内置类型一致的行为。

总之,使用引用作为赋值运算符的返回值是 C++ 中的最佳实践,它提供了更好的语义、效率和灵活性。

posted on 2017-10-04 09:15  zhangkele  阅读(3566)  评论(0)    收藏  举报

导航