- #include
- #include
- #include
- using namespace std;
-
- typedef struct data
- {
- int a;
- char str[100];
-
- } data;
- // 单木运算符
- data operator++(data &d, int) // 后置++
- {
- data temp = d;
- d.a++;
- cout << "后置++" << endl;
- return temp;
- }
-
- data operator++(data &d) // 前置++
- {
- d.a++;
- cout << "前置++" << endl;
- return d;
- }
-
- // 双目运算符
- data operator+(data &d1, data &d2) // 重载+
- {
- strcat(d1.str, d2.str);
- return d1;
- }
-
- bool operator>(data &d1, data &d2) // 重载>
- {
- return d1.a > d2.a;
- }
-
- // 位运算符重载
- ostream &operator<<(ostream &out, data &d) // 重载<< cout只能传引用
- {
- out << d.a << endl;
- out << d.str;
- return out;
- }
-
- // 重载>>
- istream &operator>>(istream &in, data &d) // 重载>>
- {
-
- in >> d.a;
- in >> d.str;
- return in;
- }
-
- int main(int argc, char const *argv[])
- {
-
- data d;
- data d1;
- d1.a = 1;
- d.a = 10;
- strcpy(d1.str, " word");
- strcpy(d.str, "hello");
-
- cout << "重载后置++" << endl;
- cout << d++.a << endl;
- cout << d.a << endl;
-
- cout << "重载前置++" << endl;
- cout << ++d.a << endl;
- cout << d.a << endl;
-
- cout << "重载+" << endl;
- cout << (d + d1).str << endl;
-
- cout << "重载>" << endl;
- cout << (d > d1) << endl;
- cout << (d1 > d) << endl;
-
- cout << "重载<<" << endl;
- cout << d << endl;
-
- cout << "重载>>" << endl;
- cin >> d;
- cout << d << endl;
- return 0;
- }

为了方便我们类操作,时常需要用到运算符重载。
对类的等号(=)操作重载需要禁止隐式转换,且要在类内对等号重载;