c语言运算符重载格式,运算符重载函数的两种形式

(1)重载为类的成员函数

格式如下:operator()

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);

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));

}

有complex c1,c2,c3;

c1+c2表示为c1.operator+(c2)其中operator+()是运算符+的重载函数。

由此得到当运算符重载为成员函数时,双目运算符仅有一个参数。单目运算符重载为成员函数时,不能再显示的说明参数。重载为成员函数时总是隐含一个参数,该参数是this指针。this指针式指向调用该成员函数对象的指针。

(2)重载为类的友元函数

重载为友元函数时,将没有隐含的参数this指针。对双目运算符有两个参数,单目运算符有一个参数

=,(),[],->不宜重载为友元函数。

格式如下:friend operator ()

class complex

{

public:

complex()

{real=imag=0;}

complex(double r,double

i)

{

real=r;

imag=i;

}

friend complex operator +(const

complex &c);

friend complex operator -(const

complex &c);

friend complex operator *(const

complex &c);

friend 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<

else

cout<

}

此时的c1+c2表示为operator +(c1,c2)

(3)通常单目运算符最好被重载为成员函数,双目运算符最好被重载为友元函数,有些情况下双目运算符不便于重载为友元函数

例如:c+4.45 c是complex对象

+重载为成员函数时有c.operator+(4.45)通过调用构造函数得到c.operator+(complex(4.45))

+重载为友元函数时有operator+(c,4.45)

通过调用构造函数得到operator+(c,complex(4.45))

若是4.45+c

成员函数对应为4.45.operator+(c)//该种方法不对

友元函数对应为operator+(complex(4.45),c)

例如

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值