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

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)

posted @ 2009-05-14 20:35  fleetwgx  阅读(253)  评论(0编辑  收藏  举报