定义 Point 类,有成员变量 X、Y,为其定义友元函数实现重载+。
解:
#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)
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题
解:
程序运行输出:
Point(10, 10)
Point(15, 15)
Point(25, 25)