C++操作符重载
来源:互联网 发布:office 2016 64位 mac 编辑:程序博客网 时间:2024/06/05 07:56
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;
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 0
- C++【操作符重载】
- c++::操作符重载
- C++:操作符重载
- 操作符重载(C++)
- C++-重载操作符<< >> = + - * /
- c++_操作符重载
- C/C++: 操作符重载案例
- C++操作符重载专题(C++)
- 类型转换和操作符重载 (c#)
- C++——操作符重载
- 重载操作符 (c++primer 4e)
- 【C++】 重载操作符类编程
- 自定义数据类型,操作符重载实例[C#]
- C++primer读书笔记8-重载操作符
- C/C++ 之 操作符重载
- [c++]实例-类array,重载操作符
- C++,重载输出操作符<<, cout.operator()
- c++string类的操作符重载
- windows下清空dns因hosts修改带来的解析缓存 ipconfig /flushdns
- iOS 定义类将请求的数据放到类中方便全局调用
- 子窗口向父窗口传值
- 在线邮件地址过滤
- captcha
- C++操作符重载
- 让windows8 变成无线路由器的方法
- logback 常用配置详解(二) <appender>
- Kali-linux下安装WineQQ2013
- oracle碎片
- infobright高性能数据仓库
- logback 常用配置详解(三) <filter>
- webrtc学习笔记(牛人博客转载)
- win7硬盘安装Ubuntu 10.04