运算符重载,友元函数,重载输入输出运算符,状态成员,rand(),类的自动转换

运算符重载:计算时间的运算符重载实例:

mytime0.h:

#ifndef MYTIME0_H_
#define MYTIME0_H_


class Time
{
private:
	int hours;
	int minutes;
public:
	Time();
	Time(int h, int m = 0);//构造函数重载
	void AddMin(int m);
	void AddHr(int h);
	void Reset(int h = 0, int m = 0);
	Time operator+(const Time&t)const;//在该函数中,不得修改类成员
	void Show()const;
};
#endif
file1:

#include<iostream>
#include"mytime0.h"
Time::Time()
{
	hours = minutes = 0;
}
Time::Time(int h, int m)
{
	hours = h;
	minutes = m;
}
void Time::AddMin(int m)
{
	minutes += m;
	hours += minutes / 60;
	minutes %= 60;
}
void Time::AddHr(int h)
{
	hours += h;
}
void Time::Reset(int h, int m)
{
	hours = h;
	minutes = m;
}
Time Time::operator+(const Time&t)const//重载+运算符
{
	Time sum;
	sum.minutes = minutes + t.minutes;
	sum.hours = hours + t.hours + sum.minutes / 60;
	sum.minutes %= 60;
	return sum;
}
void Time::Show()const
{
	std::cout << hours << "hours," << minutes << "minutes";
}

file2:

#include<iostream>
#include"mytime0.h"
int main()
{
	using std::cout;
	using std::endl;
	Time planning;
	Time coding(2, 4);
	Time fixing(5, 55);
	Time total;

	cout << "planning time=";
	planning.Show();
	cout << endl;

	cout << "coding time=";
	coding.Show();
	cout << endl;

	cout << "fixing time=";
	fixing.Show();
	cout << endl;

	total = coding + fixing;
	cout << "coding + fixing=";
	total.Show();
	cout << endl;

	Time morefixing(3, 28);
	cout << "more fixing time=";
	morefixing.Show();
	cout << endl;
	total = morefixing.operator+(total);
	cout << "morefixing.operator+(total)=";
	total.Show();
	cout << endl;

	return 0;
}
operator+即为函数名,当定义Time operator+(Time&t2)时,使用t1+t2时,实际上等价于t1.operator+(t2); 当定义Time operator+(Time&t1,Time&t2)时,使用t1+t2,实际上等价于operator(t1+t2)。

将两个以上的对象相加是允许的,如t1+t2+t3。

重载的限制:重载的运算符不必是成员函数,但必须至少有一个操作数是用户定义的类型,使用运算符时不能违反运算符原来的语法规则,不能修改优先级,不能重载某些运算符(详见prime plus第387页)


友元:友元函数不是成员函数,没有this指针,因此参数要有类的引用,如friend void show(Time&t)
例子:

friend Time operator*(double m,const Time&t)//类声明中的友元函数
Time operator*(double m, const Time&t)//定义
{
	Time result;
	long totalminutes = t.hours*mult * 60 * t.mult;
	result.hour = totalminutes / 60;
	result.minutes = totalminutes % 60;
	return result;
}
虽然友元函数不是成员函数,但它与成员函数的访问权限相同。

cout是ostream类的对象。

重载ostream的方法:首先先声明为友元函数,然后:

ostream& operator<<(ostream&os, const Time&t)//参数顺序不能倒
{
	os << t.hour << " hours, " << t.minutes << " minutes";//把类成员数据提取到os对象后返回
	return os;
}

重载运算符作成员函数还是非成员函数:

t1 = t2.operator+(t3);//成员函数
t1 = operator+(t2, t3);//非成员函数



强制类型转换:
Stonwt myCat
myCat = 19.2
//程序使用构造函数Stonwt(double)来创建一个临时对象,并将19.2作为初值。随后使用逐成员赋值方式
//将该临时对象内容复制到mycat
explicit Stonewt(double lbs)//禁止类似如上的隐式转换,但仍允许显式转换,如mycat=stonwt(19.2)




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值