C++运算符重载练习一

定义Point类,有坐标x,y两个成员变量,利用友元函数对Point类重载“++”运算符,实现对坐标值沿着平行于y=x的向上改变1。具体要求如下:

  • 编写程序定义Point类,在类中定义整型的私有成员变量x,y;

  • 在类中定义两个友元函数,分别重载前置++和后置++;

  • 编写主函数测试。

注意函数有无返回值的区别,以及返回值是否带有&引用符号。

#include <iostream>
using namespace std; 
class Point {
private:
    int x, y;

public:
    Point(int x = 0, int y = 0) : x(x), y(y) {}

    // 前置++运算符重载
    friend Point& operator++(Point& p);

    // 后置++运算符重载
    friend Point operator++(Point& p, int);

    void display() {
        std::cout << "(" << x << ", " << y << ")" << std::endl;
    }
};

// 前置++运算符重载实现
Point& operator++(Point& p) {
    p.x += 1;
    p.y += 1;
    return p;
}

// 后置++运算符重载实现
Point operator++(Point& p, int) {
    Point temp = p;
    p.x += 1;
    p.y += 1;
    return temp;
}

int main() {
    Point p1(2, 3);
    cout << "原始坐标:";
    p1.display();

    ++p1; // 使用前置++运算符
    cout << "使用前置++运算符后的坐标:";
    p1.display();

    p1++; // 使用后置++运算符
    cout << "使用后置++运算符后的坐标:";
    p1.display();

    return 0;
}

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值