运算符重载详解(一)

1.运算符重载的方法
运算符重载的方法是定义一个重载运算符的函数,使指定的运算符不仅能实现原有的功能,而且能实现在函数中指定的新的功能。在使用被重载的运算符时,系统就自动调用该函数,以实现相应的功能。
运算符重载实质上是函数的重载。
重载运算符的函数一般格式如下:
函数类型 operator 运算符名称 (形参表){
对运算符的重载处理
}
如:operator +()、operator + () 、operator+ ()、operator+(),书写方式都可以
注意:函数名是由operator和运算符组成。如 “operator +”就是函数名**斜体样式
例子1:通过函数来实现复数相加

class Complex{
public:
	Complex(){ real = 0, imag = 0; } //定义构造函数
	Complex(double r, double i){ real = r, imag = i; }//构造函数重载
	Complex complex_add(Complex &c2);		//声明复数相加函数
	void display();
private:
	double real;	//实部
	double imag;	//虚部
};
Complex Complex::complex_add(Complex &c2){
	Complex c;
	c.real = real + c2.real;
	c.imag = imag + c2.imag;
	//c.real = this->real + c2.real;  //第一种
	//c.imag = this->imag + c2.imag;
	//c.real = (*this).real + c2.real; //第二种
	//c.imag = (*this).imag + c2.imag;
	return c;
}
void Complex::display()
{	cout << real << "," << imag << "i" << endl; }
int main(){
	Complex c1(3, 4), c2(5, -10), c3; 
	c3 = c1.complex_add(c2); //调用复数相加函数
	cout << c3.display();  //8,-6i
	return 0;
}

例子2:通过运算符“+”重载来实现复数相加

class Complex
{
public:
	Complex(){ real = 0, imag = 0; } //定义构造函数
	Complex(double r, double i){ real = r, imag = i; }//构造函数重载
	Complex operator +(Complex &c2);		//声明复数相加函数
	void display();
private:
	double real;	//实部
	double imag;	//虚部
};
Complex Complex::operator +(Complex &c2)
{
	//①
	Complex c;
	c.real = real + c2.real;
	c.imag = imag + c2.imag;
	//c.real = (*this).real + c2.real; //第一种
	//c.imag = (*this).imag + c2.imag;
	//c.real = this->real + c2.real;   //第二种
	//c.imag = this->imag + c2.imag;
	return c;
    //②
//或者用一行表示
//return Complex(real + c2.real, imag + c2.imag); //该句创建一个临时对象,它没有对象名,是一个无名对象。在建立临时对象过程中调用构造函数,return语句将此临时对象作为函数返回值。
}
void Complex::display()
{
	cout << real << "," << imag << "i" << endl;
}
int main()
{
	Complex c1(3, 4), c2(5, -10), c3; 
	c3 = c1 + c2; //调用复数相加函数
	cout << c3.display();
	return 0;
}

注:将运算符+重载为类的成员函数后,C++编译系统将程序中的表达式c1 + c2 解释为

c1.operator +(c2); //其中c1和c2是Complex类的对象

如何操作常量和复数相加

c3 = 3 + c2; 			//是错误的,与形参类型不匹配
c3 = Complex(3,0) + c2; //正确,类型均为对象

2.重载运算符规则
<1>C++不允许用户自己定义新的运算符,只能对已有的C++运算符进行重载
<2>C++允许重载的运算符
绝大部分运算符可以重载。
不能重载的运算符只有5个:
成员访问运算符、成员指针访问运算符(*)、域运算符(::)、长度运算符(sizeof)、条件运算符(?:)
<3>重载不能改变运算符运算对象(即操作数)的个数。
<4>重载不能改变运算符的优先级别。
<5>重载不能改变运算符的结合性。
<6>重载运算符的函数不能有默认的参数。
<7>重载的运算符必须和用户定义的类型的对象一起使用,其参数至少应有一个是类的对象(或类对象的引用)。
<8>用于类对象的运算符一般必须重载,但有两个例外,运算符“=”和“&”不必用户重载。
<9>从理论上说,可以将一个运算符重载为执行任意的操作。如,将“>”运算符重载为“<”运算,但这样违背了运算符重载的初衷,非但没有提高可读性,反而使人无法理解程序。应当是重载运算符的功能类似于该运算符作用于标准类型时所能实现的功能。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值