C++之重载运算符

C++重载运算符


重载运算符
C++中很多内置数据类型都支持如"+"、"-"、"="、"<"等运算符,这使得表达式非常的简洁。但很多情况下,我们也希望自已定义的一些数据结构也支持类似的运算符。C++提供了这样一种机制,支持我们在不同的数据类型下对运算符进行重载,于是我们可以让自己定义的数据类型同样支持运算符。下面列出 C++支持重载的运算符

类型 运算符
双目算术运算符 +(加) 、-(减)、* 、/ 、%
单目运算符 + (正)、-(负)、*(指针) 、&(取址)
关系运算符 >、<、>=、<=、==、!=
逻辑运算符 | |、&&、!
位运算符 &、|、^、~、<<、>>
赋值运算符 =、+=、-=、*=、=、%=、&=、|=、^=、<<=、>>=
其他运算符 ++、–、[]、,(逗号)、->、()(函数)、new、delete、new[]、delete[]、<<(流)、>>

不可重载的运算符:
1.成员访问运算符(.)
2.成员指针访问运算符(.*和->* ),
3.域运算符(::)、
4.长度运算符(sizeof)、
5.条件运算符(?:)、
6.预处理符号(#)

下面看一个简单的例子:

#include <iostream>
using namespace std;
struct Point {
public:
	int x, y;
	Point(int a, int b) :x(a), y(b) {};
	Point(int a) :x(a), y(a) {};
};
Point operator+(const Point& A, const Point& B) {
	return Point(A.x + B.x, A.y + B.y);
}
int main() {
	Point p1(2, 2);
	Point p2(3, 4);
	Point p3 = p1 + p2;
	cout << p3.x << " " << p3.y << endl;
	return 0;
}

例中,为Point结构体重载了"+“运算符,传入的参数是要求和的两个结构体,返回一个新的结构体,它的x和y值是传入的两个结构体的对应值之和。重载了”+"运算符之后就可以通过"p1+p2"的形式对两个结构体求和了。

在上面例子的基础上再对"<<“流运算符进行重载,使Point支持”<<"操作。

#include <iostream>
using namespace std;
struct Point {
public:
	int x, y;
	Point(int a, int b) :x(a), y(b) {};
	Point(int a) :x(a), y(a) {};
};
Point operator+(const Point& A, const Point& B) {
	return Point(A.x + B.x, A.y + B.y);
}
ostream& operator<<(ostream& out, const Point& B) {	
	out << "(" << B.x << ", " << B.y << ")";
	return out;
}
int main() {
	Point p1(2, 2);
	Point p2(3, 4);
	Point p3 = p1 + p2;
	cout << p3 << endl;
	return 0;
}

这里对"<<“运算符进行了重载,函数的第一个参数类型是ostream的引用,表示输出流,第二个参数类型是结构体Point的引用,在函数中将Point的变量按照自定义的规则流入到第一个参数所引用的ostream中,然后返回所引用的ostream。重载了”<<“运算符后,Point就可以通过”<<"运算符输出以自定义的格式输出到标准输出了。

重载"-“和”<"运算符:

#include <iostream>
using namespace std;
struct Point {
public:
	int x, y;
	Point(int a, int b) :x(a), y(b) {};
	Point(int a) :x(a), y(a) {};
};
Point operator+(const Point& A, const Point& B) {//加
	return Point(A.x + B.x, A.y + B.y);
}
Point operator-(const Point &A) {//负
	return Point(-A.x, -A.y);
}
ostream& operator<<(ostream& out, const Point& B) {//流
	out << "(" << B.x << ", " << B.y << ")";
	return out;
}
bool operator<(const Point& A, const Point& B) {//小于
	return A.x < B.y;
}
int main() {
	Point p1(2, 2);
	Point p2(3, 4);
	Point p3 = p1 + p2;//(5, 6)
	Point p4 = -p3;	   //(-5, -6)
	cout << p3 << " " << p4 << " " << (p1 < p2) << endl;
	return 0;
}

例子中对-(取负)、<(小于)进行了重载,因此可以直接对用-Point格式对Point取负,用Point1<Point2对两个结构体进行比较。这里的<(小于)运算符在一些STL中的算法中是很有用的。

注意事项
1.重载运算符无法改变运算符的原有结构形式
2.重载运算符不能改变操作数的个数
3.重载运算符无法改变运算的优先级

猜你喜欢

转载自blog.csdn.net/weixin_43374723/article/details/83958561
今日推荐