编写程序定义Point类,有数据成员X,Y,为其定义友元函数实现重载+。

#include

class Point
{
public:
   Point() { X = Y = 0; }
   Point( int x, int y ) { X = x; Y = y; }
   void Print() { cout << "Point(" << X << ", " << Y << ")" << endl; }
   friend Point operator+( Point& pt, int nOffset );
   friend Point operator+( int nOffset, Point& pt );
private:
   int X;
   int Y;
};

Point operator+( Point& pt, int nOffset )
{
Point p = pt;
p.X += nOffset;
p.Y += nOffset;

return p;
}

Point operator+( int nOffset, Point& pt )
{
Point p= pt;
p.X += nOffset;
p.Y += nOffset;

return p;
}

void main()
{
  Point pt( 10, 10 );
  pt.Print();
 
  pt = pt + 5; // Point + int
  pt.Print();
 
  pt = 10 + pt; // int + Point
  pt.Print();
}

你可能感兴趣的:(编写程序定义Point类,有数据成员X,Y,为其定义友元函数实现重载+。)