您的位置:首页 > 其它

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

2010-05-31 16:40 363 查看
#include <iostream.h>

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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐