More Effective C++ 阅读笔记(六)--哪些运算符不能重载
2008-08-06 09:33
513 查看
More Effective C++ 阅读笔记(六)--哪些运算符不能重载
黑月亮 发表于 2005-10-3 16:22:00
下面这些操作符不能重载
"&&" ,"||" , "," , "." , ".*" , "::" , "?:"
new delete sizeof typeid
static_cast dynamic_cast const_cast reinterpret_cast
下列操作符你可以重载
operator new operator delete
operator new[] operator delete[]
+ - * / % ^ & | ~
! = < > += -= *= /= %=
^= &= |= << >> >>= <<= == !=
<= >= && || ++ -- , ->* ->
() []
原因
例如:
if (expression1 && expression2) ...
对于编译器来说,等同于下面代码之一:
if (expression1.operator&&(expression2)) ... // when operator&& is a member function
if (operator&&(expression1, expression2)) ... // when operator&& is a global function
这好像没有什么不同,但是函数调用法与短路求值法是绝对不同的。首先当函数被调用时,需要运算其所有参数,所以调用函数functions operator&& 和 operator||时,两个参数都需要计算,换言之,没有采用短路计算法。第二是C++语言规范没有定义函数参数的计算顺序,所以没有办法知道表达式1与表达式2哪一个先计算。完全可能与具有从左参数到右参数计算顺序的短路计算法相反。
因此如果你重载&&或||,就没有办法提供给程序员他们所期望和使用的行为特性,所以不要重载&&和||。
黑月亮 发表于 2005-10-3 16:22:00
下面这些操作符不能重载
"&&" ,"||" , "," , "." , ".*" , "::" , "?:"
new delete sizeof typeid
static_cast dynamic_cast const_cast reinterpret_cast
下列操作符你可以重载
operator new operator delete
operator new[] operator delete[]
+ - * / % ^ & | ~
! = < > += -= *= /= %=
^= &= |= << >> >>= <<= == !=
<= >= && || ++ -- , ->* ->
() []
原因
例如:
if (expression1 && expression2) ...
对于编译器来说,等同于下面代码之一:
if (expression1.operator&&(expression2)) ... // when operator&& is a member function
if (operator&&(expression1, expression2)) ... // when operator&& is a global function
这好像没有什么不同,但是函数调用法与短路求值法是绝对不同的。首先当函数被调用时,需要运算其所有参数,所以调用函数functions operator&& 和 operator||时,两个参数都需要计算,换言之,没有采用短路计算法。第二是C++语言规范没有定义函数参数的计算顺序,所以没有办法知道表达式1与表达式2哪一个先计算。完全可能与具有从左参数到右参数计算顺序的短路计算法相反。
因此如果你重载&&或||,就没有办法提供给程序员他们所期望和使用的行为特性,所以不要重载&&和||。
相关文章推荐
- More Effective C++ 阅读笔记(六)--哪些运算符不能重载
- C++中有哪些运算符不能重载?
- More Effective C++ 阅读笔记(九)--要用引用(reference)捕获异常
- C++之尽量不要重载&&,||或者,运算符(7)---《More Effective C++》
- effective c++ and more第二次阅读之笔记
- MoreEffective C++ 阅读笔记(一)---point 和 reference的区别
- More Effective C++ 阅读笔记(八)--“抛出一个异常”与“传递一个参数”或“调用一个虚函数”间的差异
- more effective C++阅读笔记
- &lt;More Effective C++&gt;笔记--运算符
- More Effective C++ 阅读笔记(二) -- C++的新型类型转换(造型Cast)
- More Effective C++ 阅读笔记(十)--效率问题
- 侯捷 more effective c++(WQ中文版) 阅读笔记1
- (大卫的阅读笔记)More Effective C++ Item 附2:一个auto_ptr的实现实例
- More Effective C++ 阅读笔记(三)-- placement new操作符
- More Effective C++ 阅读笔记(十一)--怎样让构造函数和非成员函数虚拟化
- <More Effective C++>笔记--运算符
- More Effective C++ 阅读笔记(四)-- 避免使用隐式类型转换
- More Effective C++ 阅读笔记(十二)--怎样限制实例化对象的数量
- More Effective C++ 阅读笔记(五)-- ++与--的前缀、后缀的区别
- More Effective C++ 阅读笔记(十三)--要求或禁止在堆中产生对象