简介:(注意前后++的写法,以及输入输出重载的写法,关键在于什么时候用&引用以及什么时候const.由于目前不知道该怎样解释,就暂且落下,自己去多多琢磨。)
运算符重载:在类或结构中,对运算符进行重新的定义,让这个运算符能适应这个类型的操作。
代码学习:(写了更多注释,方便理解)
//运算符重载 #include<iostream> using namespace std; class MyPoint{ int x; int y; public: MyPoint(){}; MyPoint(int x,int y){ this->x = x; this->y = y; }; ~MyPoint(){}; //实现两个点的矢量相加 MyPoint operator+(const MyPoint& srcPoint){//运算符重载实现两个坐标相加 MyPoint temp; temp.x = this->x + srcPoint.x; temp.y = this->y + srcPoint.y; return temp; } MyPoint operator-(const MyPoint& srcPoint){//运算符重载实现两个坐标相加 MyPoint temp; temp.x = this->x - srcPoint.x; temp.y = this->y - srcPoint.y; return temp; }//运算符重载一般this 算一个参数,所以可以少写一个参数,如果非要多 //写这个参数,就用友元,不属于类 //对于双目运算符来说,因为类中的函数自带this指针,所以只需要一个参数。如果只想 //两个参数的话,那么可以在函数前加上friend. friend MyPoint operator*(const MyPoint& p1, const MyPoint& p2); MyPoint& operator++(){//前加加 this->x++; this->y++; return *this;//this 是指针,*(this)解引用就是一个对象 } MyPoint operator++(int){//后加加 MyPoint temp = *this; this->x++; this->y++; return temp; } friend istream& operator>>(istream& is,MyPoint& src){ is >> src.x;//输入流重载 is >> src.y; return is; } friend ostream& operator<<(ostream& os,const MyPoint& src){ os << "(" << src.x << "," << src.y << ")" << endl; return os;//输出流重载 } void getPoint(){ cout << "(" << x << "," << y << ")" << endl; } }; MyPoint operator*(const MyPoint& p1, const MyPoint& p2){ MyPoint temp; temp.x = (p1.x)*(p2.x); temp.y = (p1.y)*(p2.y); return temp; } int main(){ cout << "运算符重载测试:初始坐标m1(1,2),m2(2,3):" << endl; MyPoint m1(1,2); MyPoint m2(2,3); cout << "----------------------------" << endl; cout << "运算符重载相加:" << endl; MyPoint m=m1 + m2;//隐式调用运算符重载+ m.getPoint(); cout << "----------------------------" << endl; cout << "运算符重载相减:" << endl; MyPoint m3; m3 = m1.operator-(m2);//显示调用运算符重载- m3.getPoint(); cout << "----------------------------" << endl; cout << "运算符重载相乘:" << endl; MyPoint m4 = m1*m2; m4.getPoint(); cout << "----------------------------" << endl; cout << "运算符重载前++:" << endl; cout << (++m2) << endl; cout << "----------------------------" << endl; cout << "运算符重载后++:" << endl; cout <<(m2++)<< endl; cout << "----------------------------" << endl; cout << "运算符重载输入:" << endl; MyPoint m7; cin >> m7; cout << "运算符重载输出:" << endl; cout << m7 << endl; cout << "----------------------------" << endl; return 0; }
这辈子没啥多的想法,多赚钱娶个漂亮老婆·········加油··········