C++中运算符重载

  通过对C++中的运算符号进行重载,类就可以正常的使用这些运算符号,更加直观,形象。

运算符的重载一般分为两种形式:
1、在类中声明运算符重载友元函数,然后用全局函数来实现

2、用类的成员函数来实现运算符号重载。

class Complex 
{
public:
	friend ostream& operator<<(ostream &out, Complex &c1);
	friend Complex operator+(Complex &c1, Complex &c2);
	friend Complex operator*(Complex &c1, Complex &c2);
	//friend Complex& operator++(Complex &c1); //前置++ ++c1 用友元函数
	Complex & operator++()
	{
		this->a++;
		this->b++;
		return *this;
	}
	Complex  operator++(int) //c1++ 后置,先返回,后自增
	{
		Complex tmp = *this;
		this->a++;
		this->b++;
		return tmp;
	}
	Complex (int _a, int _b)
	{
		this->a = _a;
		this->b = _b;
	}
	~Complex()
	{
		cout<<"bye"<<endl;
	}
	Complex operator-(Complex &c2)
	{
		Complex tmp(a - c2.a, this->b - c2.b);
		return tmp;
	}
	void print()
	{
		cout<<"a"<<a<<"\tb:"<<b<<endl;	
	}

protected:
private:
	int a;
	int b;
};

 

运算符重载函数全局函数的实现方法:

Complex operator*(Complex &c1, Complex &c2)
{
	Complex c(c1.a * c2.a , c1.b * c1.b);
	return c;
}
//自增操作 全局函数实现++ 的运算符号重载
//Complex& operator++(Complex &c1)
//{
//	c1.a++;
//	c1.b++;
//	return c1;
//}

Complex operator+(Complex &x, Complex &y)
{
	Complex c(x.a + y.a, x.b + y.b);
	return c;
}

//这样的话就支持链式编程
ostream& operator<<(ostream &out, Complex &c1)
{
	out<<"a:"<<c1.a<<"\t b:"<<c1.b<<endl;
	return out;
}

 

测试的主函数:

int main()
{
	Complex c1(2,3), c2(3,4);
	c1.print();
	c2.print();
	Complex c3 = c1 + c2;
	++c3;//这样调用 是全局的方法
	cout<<c3<<c1;//支持链式编程。
	c3++;
	c3.print();
	cout<<c3;
	return 0;
}

 备注:learnCpluseplus/FunctionAndReload/dm05_reload.cpp

posted @ 2016-12-15 22:12  zhangjingle  阅读(239)  评论(0)    收藏  举报