C++编译时多态----运算符重载

1、运算符重载的本质
    可以把运算符看成一个函数名,通过函数重载的方式为同一个运算符实现不同规则的运算。所以运算符重载的本质就是函数重载,两者唯一区别就是函数名,运算符重载的函数名由关键字operator和其后要重载的运算符符号构成,在形式上比普通函数名复杂。

运算符函数定义的一般格式如下:
    数据类型 operator<运算符符号>(<参数表>)

2、运算符重载的规则
      除了对象访问成员‘.’,成员指针运算符'.*'、作用域运算符'::'、“sizeof”运算符和三目运算符“?”之外,C++中所有自带运算符都可以重载,但是合法的运算符重载还有以下4个规则:
     (1)重载之后的运算符不能改变运算符的优先级和结合性;
     (2) 重载之后的运算符不能改变运算符操作数的个数和语法结构;
     (3)重载的运算符至少有一个自定义类型的;
     (4)重载的运算符函数不能有默认的参数;
3、运算符重载的实现形式
     (1)重载为类的成员函数;
     (2)重载为类的非成员函数,非成员函数通常是友元;

4、举例说明成员函数和友元函数的重载形式
    (1)   成员函数运算符:
       <函数类型> operator <运算符>(<参数表>)
{

        <函数体>
}

  调用方式:<对象名>.operator<运算符>(<参数表>)    
    (2)友元函数运算符:

       friend<函数类型>operator<运算符>(<参数表>)
  {
       <函数体> 
  }

调用方式:opeartor<运算符>(<参数一>,<参数二>)
5、两种重载方式的比较

    在多数情况下,将运算符重载为类的成员函数和类的友元函数都可以,但有些场合只能使用成员函数的形式,如 =、()、【】、->不能重载为类的友元函数,只能重载为成员函数形式。

6、运算符重载举例
      此处例举的是四则运算符重载
#include <iostream.h>
 
class complex
{
public:
complex() { real=imag=0; }
complex(double r, double i)
{
real = r, imag = i;
}
complex operator +(const complex &c);
complex operator -(const complex &c);
complex operator *(const complex &c);
complex operator /(const complex &c);
friend void print(const complex &c);
private:
double real, imag;
};
 
inline complex complex::operator +(const complex &c)
{
return complex(real + c.real, imag + c.imag);
}
 
inline complex complex::operator -(const complex &c)
{
return complex(real - c.real, imag - c.imag);
}
 
inline complex complex::operator *(const complex &c)
{
return complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
 
inline complex complex::operator /(const complex &c)
{
return complex((real * c.real + imag + c.imag) / (c.real * c.real + c.imag * c.imag),
(imag * c.real - real * c.imag) / (c.real * c.real + c.imag * c.imag));
}
 
void print(const complex &c)
{
if(c.imag<0)
cout<<c.real<<c.imag<<'i';
else
cout<<c.real<<'+'<<c.imag<<'i';
}
 
void main()
{
complex c1(2.0, 3.0), c2(4.0, -2.0), c3;
c3 = c1 + c2;
cout<<"/nc1+c2=";
print(c3);
c3 = c1 - c2;
cout<<"/nc1-c2=";
print(c3);
c3 = c1 * c2;
cout<<"/nc1*c2=";
print(c3);
c3 = c1 / c2;
cout<<"/nc1/c2=";
print(c3);
c3 = (c1+c2) * (c1-c2) * c2/c1;
cout<<"/n(c1+c2)*(c1-c2)*c2/c1=";
print(c3);
cout<<endl;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值