#include<iostream>
using namespace std;
class Complex {
public:
friend ostream& operator<<(ostream& cout, Complex& c);
Complex() {};
Complex(int x, int y) {
this->a = x;
this->b = y;
}
//重载前置++运算符
Complex& operator++() {
this->a++;
this->b++;
return *this;
}
//重载后置++运算符
Complex operator++(int) {
Complex temp = *this;
a++;
b++;
return temp;
}
/*
void operator<<(ostream &cout) {
cout << "a=" << a << endl;
cout << "b=" << b << "i" << endl;
}
*/
Complex operator+(Complex& c2) {
Complex temp;
temp.a = this->a + c2.a;
temp.b = this->b + c2.b;
return temp;
}
void display() {
cout << "a=" << a << endl;
cout << "b=" << b << "i" << endl;
}
private:
int a;
int b;
};
ostream& operator<<(ostream& cout, Complex &c) {//本质是operator<<(cout,p),简化的话就变成cout<<p
cout << "利用全局函数重载左移运算符" << endl;
cout << "a=" << c.a << " " << "b=" << c.b << 'i' << endl;
return cout;
}
int main() {
Complex c1(10, 20);
Complex c2(1, 2);
Complex c3 = c1 + c2;
c3.display();
//成员函数本质调用是
c3 = c1.operator+(c2);
//全局函数本质调用是
//c3 = operator+(c1, c2);
//c3 << cout;
cout << c3;
cout << c3 << endl;
cout << "现在是前置++" << endl;
cout << ++c3 << endl;
cout << ++(++c3) << endl;
/*
cout << "现在是后置++" << endl;
cout << c3++ << endl;
cout << (c3++)++ << endl;
*/
//会报错,因为你已经重载过<<左移运算符了,它的操作对象是一个类,而后置++返回的是一个数
c3++;
cout << c3 << endl;
++c3;
cout << c3 << endl;
}
运算符重载训练
最新推荐文章于 2021-09-25 12:15:49 发布