zoukankan
html css js c++ java
再看C++(6)操作符重载
操作符重载看上去很神秘,其实也就是是个函数,只是为了方便人们自然思维的形式,使得用操作符重载这一东东,操作符的格式如下
operator
op(aument
-
list)
如加号 operator +(aument-list)
调用时则是调用这个函数。下面是对于C++Primer 的一个例子设计一个Time的类来进行时间的相加
class
Time
{
private
:
int
m_hours;
int
m_mins;
public
:
void
AddHour(
int
hour);
void
AddMin(
int
minute);
void
Reset(
int
hour,
int
min);
Time Sum(
const
Time
&
t)
const
;
Time();
void
Show()
const
;
virtual
~
Time();
}
;
实现
Time::Time()
{
m_hours
=
0
;
m_mins
=
0
;
}
Time::
~
Time()
{
}
void
Time::AddHour(
int
hour)
{
m_hours
+=
hour;
}
void
Time::AddMin(
int
minute)
{
m_mins
+=
minute;
m_hours
+=
m_mins
/
60
;
m_mins
%=
60
;
}
void
Time::Reset(
int
hour,
int
min)
{
m_hours
=
hour;
m_mins
=
min;
}
Time Time::Sum(
const
Time
&
t)
const
{
Time result;
result.m_hours
=
m_hours
+
t.m_hours;
result.m_mins
=
m_mins
+
t.m_mins;
result.m_hours
+=
result.m_mins
/
60
;
result.m_mins
%=
60
;
return
result;
}
void
Time::Show()
const
{
std::cout
<<
m_hours
<<
"
:
"
<<
m_mins
<<
std::endl;
}
现在要实现+操作符重载由于功能和sum是一样的,所以只需要把sum的名字换成operator+就行了,其他完全不用改
Demo
查看全文
相关阅读:
Linux 文件系统相关的基本概念
Logstash : 从 SQL Server 读取数据
Windows 下配置 Logstash 为后台服务
通过 Filebeat 收集 ubuntu 系统日志
Logstash Multiple Pipelines
零基础学编程
2017年计划
2016年的年终总结
订阅《通往财富自由之路》3个月后,我做出了哪些改变
2016年第20本:社交红利2.0
原文地址:https://www.cnblogs.com/yukun/p/926648.html
最新文章
.NET:Threading and Exceptions
.NET:race conditions
经验:使用 Cache 时注意 DateTime.Now
Scala:Functions and Closures
Scala:Functional Objects
编码原则:最小化使用控制结构(条件和循环)续:告别 break 和 continue
Scala:Method 小技巧,忽略result type之后的等号
Scala:Next Steps in Scala
Scala:First Steps in Scala
Scala:HelloWorld
热门文章
编码原则:表驱动法
.NET:OrderBy和ThenBy
Scala:使用Sublime开发Scala
Scala:Object-Oriented Meets Functional
WCF:又是枚举惹的祸
Linux grep 命令
Linux ln 命令
Linux 文件与目录
Linux AUFS 文件系统
Linux EXT2 文件系统
Copyright © 2011-2022 走看看