• 软件测试技术
  • 软件测试视频
  • 开源软件测试技术
  • 软件测试沙龙
  • 软件测试资料下载
  • 软件测试杂志
  • 软件测试人才招聘

字号: | 推荐给好友 上一篇 | 下一篇

Google C++ Style Guide

发布: 2008-7-07 12:32 | 作者: Google | 来源: 领测软件测试网采编 | 查看: 229次 | 进入软件测试论坛讨论

领测软件测试网

? X z9T(Ew&^.K/f;e;Q

Operator Overloading

Do not overload operators except in rare, special circumstances. 软件测试技术门户`#Is^7Yq,\&x$B
link

Definition: A class can define that operators such as + and / operate on the class as if it were a built-in type.

|qO@2q

Pros: Can make code appear more intuitive because a class will behave in the same way as built-in types (such as int). Overloaded operators are more playful names for functions that are less-colorfully named, such as Equals() or Add(). For some template functions to work correctly, you may need to define operators. 软件测试技术门户o#Pv%X#KB$UV

Cons: While operator overloading can make code more intuitive, it has several drawbacks:

ch`E#m1NFVE
  • It can fool our intuition into thinking that expensive operations are cheap, built-in operations.
  • It is much harder to find the call sites for overloaded operators. Searching for Equals() is much easier than searching for relevant invocations of ==.
  • Some operators work on pointers too, making it easy to introduce bugs. Foo + 4 may do one thing, while &Foo + 4 does something totally different. The compiler does not complain for either of these, making this very hard to debug.
Overloading also has surprising ramifications. For instance, you can't forward declare classes that overload operator&.

Decision: 软件测试技术门户6_8U#sY$E#h!E"CD

7wo(LwB"p,_ H In general, do not overload operators. The assignment operator (operator=), in particular, is insidious and should be avoided. You can define functions like Equals() and CopyFrom() if you need them.

$l2g'e1K8K-r 软件测试技术门户!D(^9p.t*Oz U"B/qe

However, there may be rare cases where you need to overload an operator to interoperate with templates or "standard" C++ classes (such as operator<<(ostream&, const T&) for logging). These are acceptable if fully justified, but you should try to avoid these whenever possible. In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container. 软件测试技术门户nZ0v#bw,g6|

R7w#H|&o4l3k ln{F Some of the STL algorithms do require you to overload operator==, and you may do so in these cases, provided you document why.

-~uQ b#~