有些场景仍然需要 写成 non-member func进行隐式类型转换(implicit type conversion)
《Effective C++》 条款-24:若所有参数皆需类型转换,请为此采用 Non-member func()
举例: 写一个 operator*, 然后测试其交换律
结论:
当在 member func() 中,写成Entity operator* ( const Entity& e) 会造成不能隐式转换的问题;
当写成 non-member func()时候,写成Entity operator* ( const Entity& e1, const Entity& e2 )
可以完成隐式转换
【注】
在写 operator* 的时候,e1 * e2 return的是一个 临时值,所以函数要 return-by-value
我自己写了一个 operator *=, 可以发现返回值是自身,因此可以 return-by-reference
#include <iostream>
class Entity{
public:
// 在构造函数中给个初始值,方便后面的 * 运算
Entity( int x = 0, int y = 0) : _x(x), _y(y){
std::cout << "ctor" << std::endl;
}
Entity( const Entity& e ) : _x(e._x), _y(e._y