运算符重载
定义
- 运算符重载是对已有的运算符赋予多重含义,使同一个运算符作用于不同类型的数据时导致不同行为。
运算符重载规则
- C++运算符除了少数几个,全都可以重载,且只能重载C++已有的运算符;
- 重载后其优先级和结合性不会改变;
- 重载的功能应当与原有功能类似,不能改变原运算符的操作对象个数,同时至少要有一个操作对象是自定义类型;
返回类型 operator 运算符(形参表)
{
函数体
}
运算符重载为成员函数
//重载 + , -
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point()
{
x = 0;
y = 0;
}
Point(int a, int b) : x(a), y(b) {}
Point operator+(Point& p)
{
return Point(x + p.x, y + p.y);
}
Point operator-(Point& p)
{
return Point(x - p.x, y - p.y);
}
void display() { cout << x << " " << y << endl; }
};
int main()
{
Point a(3, 4);
Point b(4, 5);
Point c ;
c = a + b;
Point d = b - a;
c.display();
d.display();
}
结果:
//重载++, --
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point()
{
x = 0;
y = 0;
}
Point(int a, int b) : x(a), y(b) {}
Point operator++()
{
this->x++;
this->y++;
return *this;
}
Point operator++(int)
{
Point old = *this;
++(*this);
return old;
}
Point operator--()
{
this->x--;
this->y--;
return *this;
}
Point operator--(int)
{
Point old = *this;
--(*this);
return old;
}
void display() { cout << x << " " << y << endl; }
};
int main()
{
Point a(3, 4);
a.display();
(a++).display();
a.display();
(++a).display();
cout << "--------" << endl;
a.display();
(a--).display();
a.display();
(--a).display();
return 0;
}
结果:
运算符重载为非成员函数
//对+, - 进行非成员函数重载
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point()
{
x = 0;
y = 0;
}
Point(int a, int b) : x(a), y(b) {}
friend Point operator+(Point& a, Point& b)
{
return Point(a.x + b.x, a.y + b.y);
}
friend Point operator-(Point& a, Point& b)
{
return Point(a.x - b.x, a.y - b.y);
}
void display() { cout << x << " " << y << endl; }
};
int main()
{
Point a(3, 4);
Point b(4, 4);
Point c = a + b;
c.display();
}
结果: