C++学习第10课,类内运算符重载

1 先上代码



#include <iostream>

#include <string.h>

#include <unistd.h>

using namespace std;

class Point {

private:

int x;

int y;

public:

Point()

{

cout<<"Point()"<<endl;

}

Point(int x, int y) : x(x), y(y)

{

cout<<"Point(x,y)"<<endl;

}

Point(const Point &per)

{

cout<<"Point(copy)"<<endl;

x = per.x;

y = per.y;

}

~Point()

{

cout<<"~Point()"<<endl;

}

int getX(){ return x; }

int getY(){ return y; }

void setX(int x){ this->x = x; }

void setY(int y){ this->y = y; }

void printInfo()

{

cout<<"("<<x<<", "<<y<<")"<<endl;

}

/*+加法*/

Point operator+(Point &a)

{

Point n;

n.x = this->x+a.x;

n.y = this->y+a.y;

cout<<"operator+(Point &a)"<<endl;

return n;

}

Point operator++(int b)

{

Point n;

n.x = this->x++;

n.y = this->y++;

cout<<"p++"<<endl;

return n;

}

Point& operator++(void)

{

this->x++;

this->y++;

cout<<"++p"<<endl;

return *this;

}

friend ostream& operator<<(ostream& cout, Point &a);

};

/*这里是<<*/

ostream& operator<<(ostream& cout, Point &a)

{

cout<<"("<<a.x<<", "<<a.y<<")";

return cout;

}

int main(int argc, char **argv)

{

cout<<"*******************"<<endl;

Point p1(1, 2);

Point p2(2, 3);

cout<<"*******************"<<endl;

Point m1 = p1+p2;

Point m2 = p1++;

Point m3 = ++p1;

cout<<"*******************"<<endl;

cout <<"Port = "<<p1<<endl;

return 0;

}




自己看

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容