运算符重载++

xiaoxiao2021-02-27  187

#include <iostream> using namespace std ; class coplex { public: coplex(int x=0,int y=0); coplex(coplex& tem); coplex& operator ++(); coplex& operator ++(int); friend ostream& operator<< (ostream& os, coplex& cp);//这种只能重在为友元函数 private: int a; int b; }; coplex::coplex(int x, int y) { a = x; b = y; } coplex::coplex(coplex& tem){ a = tem.a; b = tem.b; } coplex& coplex::operator++(){ this->a++; this->b++; return *this; } coplex& coplex::operator++(int){ //多了一个int型占位符(只能是int型,不能是别的,如float),用来区分前置++, //系统已经定义好:带int型占位符的是后置++,不带的是前置++,要顺从,不要多想。 coplex *tem = new coplex(*this); ++(*this); //利用已经定义的前置++函数实现 return *tem; } ostream& operator<< (ostream& os, coplex& cp){ os << cp.a<<"  "<<cp.b << endl; return os; } int main(){ coplex a(1, 2); coplex b(2, 3); cout << a << b<<endl; cout << a++<< endl; cout <<++b << endl; cout << a << b << endl; system("pause"); return 0; }
转载请注明原文地址: https://www.6miu.com/read-13108.html

最新回复(0)