码迷,mamicode.com
首页 > 其他好文 > 详细

Chapter 10 Operator Overloading

时间:2021-07-05 17:20:26      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:new   强制   cout   overload   lis   eal   classname   输入   rand   

  1. 重载为成员函数

双目:

class ClassName

{

public:

 DataType operator@(Parameter List); …

};

DataType ClassName::operator@ (Parameter List) { … }

 

aa@bb    //or aa . operator @ (bb)

 

单目:

class ClassName

{

public:

DataType operator@(  ); …

};

DataType ClassName::operator@ (  ) { … }

@aa    //or aa.operator @ ( )

默认为前置

Complex operator ++ ( );

后置的话形参列表里有一个int,本身无作用只是为了区分

Complex Complex∷operator ++ ( int )

c2=c1++; //or c2=c1.operator++(0);

 

  1. 重载为友元函数

class ClassName

{

public:

friendDataType operator@(Parameter List); …

 };

DataType operator@ (Parameter List) { … }

aa@bb    //or operator @ (aa , bb)

默认为前置Complex operator ++ (Complex &c )

后置的话同理Complex operator ++ (Complex & c, int )

 

  1. 重载为成员函数:

双目运算符参数列表有一个参数,单目运算无参数

重载为友员函数:

双目运算符参数列表有两个参数,单目运算有一个参数

 

  1. Rules for Operator Overloading ?

can not define newoperators ?

can not change the numberof operands ?

can not change the precedence ?

can not change the associativity(结合性) ?

can not have default parameters ?“=”, “( )”, “[ ]”

can only be overloaded as member functions ?“.”, “.*”, “::”, “sizeof”, “?:” can not be overloaded

 

  1. 重载赋值运算符

ClassName&ClassName::operator =( const ClassName & source )

{

real= source.real; imag= source.imag; return *this; //注意返回值

}

 

  1. 重载输入输出运算符

重载为友元函数 friend ostream & operator <<(ostream & , ClassName & );

 

ostream & operator <<(ostream & , ClassName & )

{  

output<<“( ”<<c.real<<“ , ” <<c.imag<<“i )” <<endl;

return output;//注意返回值

 }

 

friend istream & operator >>(istream & , ClassName & );

istream & operator >>(istream & input, Complex &c)

{

cout<<“Input the real part and” <<“imaginary part of a” <<“complex number:”; input>>c.real>>c.imag;

return input;

 }

 

  1. 强制类型转换?

class ClassName{ public: operator DataType( ); … }

Chapter 10 Operator Overloading

标签:new   强制   cout   overload   lis   eal   classname   输入   rand   

原文地址:https://www.cnblogs.com/lipoicyclic/p/13153817.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!