【发布时间】:2018-10-10 15:10:30
【问题描述】:
我尝试为我的班级重载 operator
我看到这样做的方法是
std::ostream& operator<<(std::ostream& os, const T& obj)
{
// write obj to stream
return os;
}
What are the basic rules and idioms for operator overloading?
但是,我尝试使我的代码符合 Google C++ 风格指南 https://google.github.io/styleguide/cppguide.html#Reference_Arguments
它表示不允许在没有 const 的情况下传递引用,除非约定需要它,例如 swap()。这个重载 operator
std::ostream& operator<<(std::ostream* os, const T& obj)
^
?或不以非常量引用作为输入的东西。
如果是这样,请教我怎么做。谢谢。
【问题讨论】:
-
如果你问我,这似乎是一个非常糟糕的规则。一个危险信号是它有
swap和复制构造函数等异常。编辑:每次谷歌风格指南出现时,我都会学到一些新的东西,这让我对它失去了更多的尊重。也许它对他们很有效,但我不会推荐它。 -
google C++ 指南被广泛认为是一件坏事。
-
流参数必须是非常量引用,否则不起作用。
-
请考虑 google 指南是为 google 代码库制定的,该代码库可能有数百万个遗留问题,包括最坏的习惯,他们必须尽最大努力使其易于管理,如果您编写自己的代码,那么他们规则可以完全关闭
-
passing the reference without const is not allowed except for the case that it is needed by convention such as swap()- 我认为这就是答案。在你的情况下,我会说这是惯例所需要的。
标签: c++