operator = 为了能够连续使用 = 赋值,所以返回类型为 &,即 reference by this *

C++中,为了支持连续赋值操作,如a = b = c,`operator=`通常设计为返回一个对`this`的引用。例如:`Base& operator= ( Base& b ){}`。默认的`operator=`可能不适合某些情况,因此需要自定义以实现特定行为,如在此例子中通过赋值100来区分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

eg. Base& operator= ( Base& b ){}

【注】系统会有自带的 operaotr =, 所以我在自己写的里面 = 100以示区别

#include <iostream>

class Base{
public:
    Base( ){
        std::cout << "ctor" << std::endl;
    }
    Base( int x, int y ) : _x(x), _y(y){
        std::cout << "ctor with value" << std::endl;
    }
    ~Base( ){
        std::cout << "dtor" << std::endl;
    }

    void Print( ){
        std::cout << "x: " << _x << "  y: " << _y << std::endl;
    }

    // 自己写一个 operator=
    Base& operator= ( Base& b ){
        this->_x = b._x + 100;
        this->_y = b._y + 100;
        return *this;
    }
    

public:
    int _x, _y;
};

int main( ){
    Base a(1,2);
    Base b(3,4);
    a.Print();
    b.Print();

    a = b;
    a.Print();

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值