C++运算符重载 摘自网络

本文介绍了一个CPoint类的实现,该类通过运算符重载实现了坐标点的递增和递减操作。文中提供了完整的代码示例,并展示了如何通过前缀形式调用递增和递减操作。

1

运算符重载的问题:

 

#include<iostream.h>
#include<string.h>
#include<stdlib.h>
class CPoint
{
    int x,y;
public:
    CPoint (int vx,int vy)
    {x=vx;y=vy;}
    CPoint () {x=0;y=0;}
    void Print();
    CPoint operator++();
    CPoint operator--();
};
void CPoint::Print()
{    cout<<"("<<x<<","<<y<<")\n";}

CPoint CPoint::operator ++()
{  if (x<640) x++;
   if (y<480) y++;
   return *this;
}
CPoint CPoint ::operator --()
{
    if (x>0) x--;
    if (y>0) y--;
    return *this;
}
void main (void)
{
    CPoint p1(10,10) ,p2(200,200);
    for (int i=0;i<5;i++)
        (++p1).Print();
    cout<<"\n";
    for (i=0;i<5;i++)
        (--p2).Print();
    cout<<"\n";
}

两个关键词 this 和 operate

结果类的非静态成员函数中返回类对象本身的时候,直接使用 return *this

 

执行

image

 

为了更好分析这个代码作用,修改部分内容;

for (int i=0;i<5;i++)
    (p1++).Print();
cout<<"\n";
for (i=0;i<5;i++)
    (p2--).Print();
cout<<"\n";

compile结果如下 2个 warning 0个 error

--------------------Configuration: CPoint - Win32 Debug--------------------
Compiling...
CPoint.cpp
warning C4620: no postfix form of 'operator ++' found for type 'CPoint', using prefix form
see declaration of 'CPoint'
warning C4621: no postfix form of 'operator --' found for type 'CPoint', using prefix form
see declaration of 'CPoint'

CPoint.obj - 0 error(s), 2 warning(s)

转载于:https://www.cnblogs.com/fleetwgx/archive/2009/05/14/1457094.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值