5.25_C++

1、运算符重载的格式

T operator @(参数表)
{
重载函数体
}

其中T为返回类型,operator为关键字,@为运算符名称,参数表为参与运算的数据即操作数,可以是一个或两个,因此从所需操作数的数量上来区分,可分为单目运算符和双目运算符两种。

  • Sum
    1. 一般在对类的对象进行操作的函数中,都要能访问类中的私有数据所以要么将这些函数定义成类的成员函数,要么将它定义成类的友元函数,运算符函数的重载也是如此。
    2. 运算符函数的参数建议都声明为引用型,可以最大程度的提高运行效率,如果不希望在函数内部对参数有所改动,可以在参数前加const关键字加以限定

2、运算符重载为友元成员函数

作为友元运算符函数,首先要在相应的类中声明为该类的友元函数,声明的一般形式为:
friend 返回类型operator @(T &a, T &b);
而函数的具体定义如下:
返回类型operator @(T &a, T &b) { //函数体 〕
注意:为了提高参数传递时的效率,参数通常被声明为引用类型。

#include <iostream>
using namespace std; 
class Complex   //复数类
{
	private: 
		double image; 
		double real; 
	public: 
		Complex(double x=0.0,double y=0.0)//构造函数
		{  real  =x; image =y;  }
		void Print();
		friend Complex operator +(const Complex &c1,const Complex &c2);
};
void Complex::Print()
{
	cout<<real<<” + ”<<image<<”i”<<endl; //以复数格式输出
}
Complex operator +( const Complex &c1, const Complex &c2)	
{
	Complex temp(c1.real+c2.real,c1.image+c2.image);
	return temp;
}
int main()
{
	Complex c1(2,7),c2(4,2),c3;
	c3=c1+c2;   //表达式的完整形式应该是 c3=operator+(c1,c2)
	c3.Print();
	return 0;
}

3、运算符重载为成员函数

如果是重载双目运算符,就只要设置一个参数作为右侧运算量,而左侧运算量就是该对象本身;如果是重载单目运算符,就不必另外设置参数,运算符的操作量就是对象本身。

#include <iostream>
using namespace std;  
class Complex   //复数类
{
	private: 
		double real,image;
	public: 
		Complex(double x=0.0,double y=0.0){  real  =x; image =y;  }//构造函数
		Complex operator -(const Complex &c);//减法操作,双目运算符
		bool operator ==(const Complex &c);	//关系判断相等,双目运算符
		Complex operator -();			//求负取反,单目运算符
		Complex &operator +=(const Complex &c);//叠加操作,双目运算符
		void Print();
};
void Complex::Print()
{
	cout<<real<<” + ”<<image<<”i”<<endl; //以复数格式输出
}
Complex Complex ::operator -(const Complex &c)	
{
	Complex temp(real-c.real,image-c.image);
	return temp;
}
bool Complex ::operator ==(const Complex &c)	
{
	return (real==c.real && image==c.image);//判断分量是否全相等
}
Complex Complex ::operator -()	
{
	return Complex(-real,-image);//返回一个无名对象
}
Complex & Complex ::operator +=(const Complex &c)	
{
	real+=c.real;			//成员叠加
	image+=c.image;
    	return *this;			//返回对象的引用
}
int main()
{
	Complex c1(2,7),c2(4,2),c3;
	c3=c1-c2;       //表达式的完整形式应该是 c3=c1.operator-(c2)
	c3.Print();
	if(c3==c1)cout<<”c3 equals to c1”<<endl;//判断c3和c1是否相等
	else cout<<”c3 doesn’t equale to c1”<<endl;
	c3=-c2;		//把c3赋值为c2的求负取反值
	c3.Print();
	c3+=c2;
	c3.Print();
	return 0;
}
Tags

No responses yet

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注