前置加加重载

前置加加重载

前置加加有返回值,《可以作为左值》,可以连续赋值《返回对象的引用》

以成员函数为例 如果直接返回对象

#include <iostream>
using namespace std;

class points
{

private:
    int x;
    int y;

public:
    points(int x, int y);
    void display();

    //前置加加有返回值,所以可以作为左值,所以返回值不设置为const 。而是让对象直接自增,所以返回值类型不再是基本数据类型,
    points operator++();
};
points::points(int x = 0, int y = 0) : x(x), y(y){};

void points::display()
{
    cout << "x:   " << this->x << "y:     " << this->y;
};

points points::operator++()
{

    return points(this->x++, this->y++); //若不需要连续赋值,则返回临时对象类型
}
void test1(points &p1)
{

    ++p1;
    p1.display();
    cout << endl;
}
void test2(points &p1)
{
    ++p1 = points(55, 55); //用匿名对象直接赋值
    p1.display();
}
int main()
{
    points p1(22, 33);

    test1(p1); //演示前置加加的作用
    cout << "p1对象的值为:" << endl;
    p1.display();
    cout << endl;
    test2(p1); //演示前置加加能否被连续赋值。
    //补充说明: 返回值为对象时,会调用拷贝构造函数,而拷贝构造函数的原型   person(const person &new_object); 对象就是传引用,所以对象的值在执行完test1 函数之后,就改变了。
    //这可以从
    //当返回值不为对象引用类型时,无法做到连续赋值的情况.
}

返回对象引用的情况

(因为连续赋值的关系,每次返回,返回值必定是作为左值,就像 ++a=b; ++a先运算,返回a+1,然后a+1 继续作为左值,左值一定不能为临时变量,所以一定不能返回临时对象。)

#include <iostream>
using namespace std;

class points
{

private:
    int x;
    int y;

public:
    points(int x, int y);
    void display();

    //前置加加有返回值,所以可以作为左值,所以返回值不设置为const 。而是让对象直接自增,所以返回值类型不再是基本数据类型,
    points &operator++();
};
points::points(int x = 0, int y = 0) : x(x), y(y){};

void points::display()
{
    cout << "x:   " << this->x << "y:     " << this->y;
};

points &points::operator++()
{

    this->x++;
    this->y++;
    return *this;
    // return points(this->x++, this->y++);若不需要连续赋值
    // 1-允许进行连续赋值
    // 2- 防止返回对象(返回对象也可以进行连续赋值(常规的情况,如a = b = c,而不是(a = b) = c))的时候调用拷贝构造函数和析构函数导致不必要的开销,降低赋值运算符的效率。
}
void test1(points &p1)
{

    ++p1;
    p1.display();
}
void test2(points &p1)
{
    ++p1 = points(55, 55); //用匿名对象直接赋值
    p1.display();
}
int main()
{
    points p1(22, 33);

  test1(p1);//演示前置加加的作用

  test2(p1);//演示前置加加能否被连续赋值。
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丁金金

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值