关于C++运算符重载的一些个人总结

C++中常见的运算符重载

作为一个C++的菜鸡初学者,每次用到运算符重载的时候都需要再重新查一遍。不如一次总结好,把运算符重载相关的部分写成一个例子:

#include<iostream>
using namespace std;
class complex
{
public:
	double real;
	double imag;
	complex(double a,double b):real(a),imag(b){}
	complex():real(0),imag(0){}                                                    //这里一定要写
	complex operator+(const complex& A) {                                          //对+进行重载
		complex B;
		B.real = this->real + A.real;
		B.imag = this->imag + A.imag;
		return B;
	}
	complex operator -(const complex& A) {                                          //对-进行重载
		complex B;
		B.real = this->real - A.real;
		B.imag = this->imag - A.imag;
		return B;
	}
	complex operator ++(int) {
		this->real = this->real + 1;
		return *this;
	}
	friend bool operator >(const complex &A, const complex& B) {                  //对>进行重载
		if (A.real > B.real)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	friend bool operator <(const complex& A, const complex& B) {                 //对<进行重载
		if (A.real < B.real)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	 friend ostream &operator <<(ostream& os,const complex& A)                  //对于流运算符进行重载
	{
		os << "After operator:real:" << A.real << " imagine:" << A.imag;
		return os;
	}
	void PrintMessage()
	{
		cout << "Real:" << this->real << endl;
		cout << "Imagine:" << this->imag << endl;
	}
};
int main()
{
	complex A(1, 2);
	complex B(3, 4);
	if (A > B)
	{
		cout << "A>B" << endl;
	}
	else
	{
		cout << "A<B" << endl;
	}
	complex C = A + B;
	complex D = A - B;
	cout << A << endl;
	A++;
	A.PrintMessage();
	C.PrintMessage();
	D.PrintMessage();
	cout << endl;
}

运行结果
运行结果
写在最后:

  1. 对于流运算符为什么必须使用friend友元,我个人的理解是(欢迎大佬来指正)ostream中的对象,如本次使用的os,相对于complex来说属于类外成员,因此需要使用friend。
  2. 对于流云算为什么必须使用引用类型(ostream& os)和&operator,在多个平台查了查,ostream对象不支持复制,需要是引用(欢迎大佬来指正)。
  3. 参与运算符重载的至少有一个类。
  4. 大多数的运算符是可以重载的,但::(域运算符),.*(成员指针运算符),sizeof,?:(条件运算符)(在网上查了一下才知道名字,捂脸.jpg)不可以重载。
  5. 重载运算符不会改变运算符的优先级和其结合性。
  6. 重载函数可以定义在类内,当然也可以定义为一个友元函数。

补充:流运算符重载

#include<iostream>
using namespace std;
class A
{
public:
	int x;
	int y;
	A(int a=2,int b=3):x(a),y(b){}
	friend istream& operator>>(istream& is, A& a)   //流提取运算符 >> 重载
	{
		is >> a.x >> a.y;
		return is;
	}
	friend ostream& operator<<(ostream& os,const A& a)    //流插入运算符 >> 重载
	{
		os << a.x << " " << a.y << endl;
		return os;
	}
	void print_a()
	{
		cout << x << " " << y << endl;
	}
};
int main()
{
	A a;
	cout << a;
	cin >> a;
	cout << a;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值