C++运算符重载
运算符重载(操作符重载):可以为运算符增加一些新的功能。
class Point
{
friend Point operator+(const Point &, const Point &);
private:
int x, y;
public:
int get_x() { return this->x; }
int get_y() { return this->y; }
Point(int x, int y) : x(x), y(y) { }
void display()
{
printf("(%d, %d)\n", this->x, this->y);
}
};
Point operator+(const Point &p1, const Point &p2)
{
return Point(p1.x + p2.x, p1.y + p2.y);
}
int main()
{
Point p1(1, 2);
Point p2(3, 4);
Point p3 = p1 + p2;
// 相当于
// Point p3 = operator+(p1, p2);
p3.display();
return 0;
}
写成成员函数
也可以写成成员函数
class Point
{
private:
int x, y;
public:
Point(int x, int y) : x(x), y(y) { }
void display()
{
printf("(%d, %d)\n", this->x, this->y);
}
Point operator+(const Point &p)
{
return Point(this->x + p.x, this->y + p.y);
}
};
int main()
{
Point p1(1, 2);
Point p2(1, 2);
Point p3 = p1 + p2;
// 相当于
// Point p3 = p1.operator+(p2);
p3.display();
return 0;
}
更多运算符重载
class Point
{
friend ostream &operator<<(ostream &, const Point &);
friend istream &operator>>(istream &, Point &);
private:
int x, y;
public:
Point(int x = 0, int y = 0) : x(x), y(y) { }
void display()
{
printf("(%d, %d)\n", this->x, this->y);
}
const Point operator+(const Point &p) const
{
return Point(this->x + p.x, this->y + p.y);
}
const Point operator-(const Point &p) const
{
return Point(this->x - p.x, this->y - p.y);
}
Point &operator+=(const Point &p)
{
this->x += p.x, this->y += p.y;
return *this;
}
bool operator==(const Point &p) const
{
return this->x == p.x && this->y == p.y;
}
bool operator!=(const Point &p) const
{
return this->x != p.x || this->y != p.y;
}
const Point operator-() const
{
return Point(-this->x, -this->y);
}
// 前置++
Point &operator++()
{
this->x++, this->y++;
return *this;
}
// 后置++
const Point operator++(int)
{
Point t(this->x, this->y);
this->x++, this->y++;
return t;
}
};
ostream &operator<<(ostream &cout, const Point &p)
{
return cout << "(" << p.x << "," << p.y << ")";
}
istream &operator>>(istream &cin, Point &p)
{
return cin >> p.x >> p.y;
}
不可被重载的运算符
- 对象成员访问运算符:
.。 - 域运算符:
::。 - 三目运算符:
?:。 sizeof
有些运算符只能重载为成员函数
- 赋值运算符:
=。 - 下标运算符:
[]。 - 函数运算符:
()。 - 指针访问成员:
->。
