应用举例:
#include <iostream>
using namespace std;
class Coord
{
public:
Coord(int _x=0, int _y=0)
:x(_x), y(_y){}
//成员函数 单目运算符重载
Coord operator-()
{
Coord c;
c.x = -this->x;
c.y = -this->y;
return (c);
}
//友元函数 双目运算符重载
friend Coord operator+(Coord &k, Coord&j)
{
Coord i(0, 0);
i.x = k.x + j.x;
i.y = k.y + j.y;
return i;
}
//友元函数 流运算符重载
friend ostream& operator<<(ostream &os, Coord &c)
{
os << "[" << c.x << "," << c.y << "]";
return os;
}
friend istream& operator>>(istream&is, Coord&c)
{
is >> c.x;
is >> c.y;
return is;
}
private:
int x;
int y;
};
int main()
{
Coord a, b, c;
cin >> a >> b;
c = a + b;
cout << c << endl;
cout << -c << endl;
cout << -(-c) << endl;
system("pause");
return 0;
}
//VS2013编译通过
小结:
1.不可重载的运算符
. (成员访问运算符)
.* (成员指针访问运算符)
:: (域运算符)
sizeof (长度运算符)
?: (条件运算符)
2.只能重载为成员函数的运算符
= (赋值运算符)
[] (下标运算符)
() (函数运算符)
-> (间接成员访问)
->* (间接取值访问)
3.
【1】所有的单目运算符 一般用成员重载
【2】+= -= /= *= ^= &= != %= >>= <<=
一般用成员重载 (涉及到连续赋值)
【3】其他双目运算符 一般用 非成员
未完 待续>>>>>>