C++ Primer Plus Chapter11

Chapter11 使用类

运算符重载

运算符函数

operatorop(argument-list);

op必须是C++的有效运算符。

重载限制

  1. 重载后的运算符必须至少有一个操作数的类型为用户自定义类型
  2. 不能违反运算符原来的句法规则,不能修改运算符的优先级
  3. 不能创建新运算符
  4. 不能重载以下运算符:sizeof . .* :: ?: typeid const_cast dynamic_cast reinterpret_cast static_cast

友元

创建友元函数

将原型放在类声明中,并在原型声明前加上 friend 关键字:

friend Time operator*(double m, const Time & t);

友元函数无法用成员运算符来调用,但其访问权限与成员函数相同

定义友元函数

Time operator*(double m, const Time & t)
{
	Time res;
	long total = t.hours * mult * 60 + t.minutes * mult;
	res.hours = total / 60;
	res.minutes = total % 60;
	return res;
}

因为其不是成员函数,所以不需要Time::限定符,同时也不用关键字 friend

应用

重载 « 来显示自定义对象

ostream & operator(ostream & os, const type & obj)
{
	os << ...;	//display object contents
	return os;
}

转换函数

原型

operator typeName()

转换函数必须是类方法,转换函数无返回类型,无参数

参考书目C++ Primer Plus 第6版