C++操作符重载

柔光的暖阳◎ 2022-08-14 03:47 260阅读 0赞

C++操作符重载

1在类中重载+=操作符

赋值操作符必须定义为成员函数,无论形参为何种类型

赋值必须返回*this 的引用










1


2


3


4


5


6


7


8


9


10


11


12


13


14


15


16


17


18


19


20


21



class 
Love{


public
:


    
int 
str;


    
int 
agi;


    
int 
intel;


     


    
Love(): str(0), agi(0) , intel(0){}


    
Love(
int 
a , 
int 
b ,
int 
c): str(a), agi(b) , intel(c){};


    
Love& operator+=(
const 
Love &test){


        
str += test.str;


        
agi += test.agi;


        
intel += test.intel;


        
return 
*
this
;


    
}


};


int 
main(){


    
Love boy ,girl(10,20,30);


    
boy += girl;


    
cout << boy.str << boy.agi << boy.intel << endl;


    
return 
0;


}

在类外面重载+号










1


2


3


4


5


6


7


8


9


10


11


12


13


14


15


16


17



class 
Love{


public
:


    
int 
str;


    
int 
agi;


    
int 
intel;


     


    
Love(): str(0), agi(0) , intel(0){}


    
Love(
int 
a , 
int 
b ,
int 
c): str(a), agi(b) , intel(c){};


};


//为了与内置操作符保持一致,加法返回一个右值,而不是引用


Love operator+(
const 
Love &fir, 
const 
Love &sec){


    
Love ans;


    
ans.str = fir.str + sec.str ;


    
ans.agi = fir.agi + sec.agi ;


    
ans.intel = fir.intel + sec.intel;


    
return 
ans;


}

在类外面的输入输出操作符

为什么IO操作符必须为非成员函数?

因为做操作数只能是该类类型的对象

比如 Love item;

  1. item << cout ;

由于IO操作符通常对非公用数据成员进行读写,所以通常将IO操作符

设定为友元










1


2


3


4


5


6


7


8


9


10


11


12


13


14


15


16


17


18


19


20


21


22


23


24


25


26



class 
Love{


public
:


    
int 
str;


    
int 
agi;


    
int 
intel;


     


    
Love(): str(0), agi(0) , intel(0){}


    
Love(
int 
a , 
int 
b ,
int 
c): str(a), agi(b) , intel(c){};


    
friend 
istream& operator>>


            
(istream& , Love&);


    
friend 
ostream& operator<<


            
(ostream& , 
const 
Love&);


};


//要有处理错误和文件结尾的措施


istream& operator>>(istream& in, Love &s){


        
in >> s.str >> s.agi >> s.intel;


        
if
( !in )


            
Love(0,0,0);


        
return 
in;


}


ostream&


operator<<(ostream& out ,
const 
Love &s){


    
out << 
“str:=” 
<< s.str << 
“ agi:=”


        
<< s.agi << 
“ Int:=” 
<< s.intel;


    
return 
out;


}

发表评论

表情:
评论列表 (有 0 条评论,260人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C++操作符重载

    又看了一遍操作符的东西,感觉之前对操作符的理解还停留在很浅的认知上(仅仅会用哈哈),所以做一下笔记来加深一下印象。 文章目录 一、为什么会有操作符重载

    相关 C++中操作符重载

    一、操作符重载属于什么? 在本文开始阐述之前,首先明确,操作符重载是一个具有特殊名的“ 函数 ”。 既然作为函数,那么,就具有函数的特性,一是形参表,二是返回值。 关键字