首页 > 试题广场 >

定义 Point 类,有成员变量 X、Y,为其定义友元函数实

[问答题]

定义 Point 类,有成员变量 XY,为其定义友元函数实现重载+


推荐

解:

#include <iostream.h>
class Point
{
public:
Point() { X = Y = 0; }
Point( unsigned x, unsigned y ) { X = x; Y = y; }
unsigned x() { return X; } 
unsigned y() { return Y; }
void Print() { cout << "Point(" << X << ", " << Y << ")" << endl; }
friend Point operator+( Point& pt, int nOffset ); 
friend Point operator+( int nOffset, Point& pt );
private: 
unsigned X; 
unsigned Y; 
};
Point operator+( Point& pt, int nOffset )
{
Point ptTemp = pt;
ptTemp.X += nOffset;
ptTemp.Y += nOffset;
return ptTemp;
}
Point operator+( int nOffset, Point& pt )
{
Point ptTemp = pt;
ptTemp.X += nOffset;
ptTemp.Y += nOffset;
return ptTemp;
}
void main()
{
Point pt( 10, 10 ); 
pt.Print();
pt = pt + 5; // Point + int
pt.Print();
pt = 10 + pt; // int + Point
pt.Print();
}

程序运行输出:

Point(10, 10)

Point(15, 15)

Point(25, 25)



发表于 2018-04-18 20:38:24 回复(0)