简体   繁体   English

重载运算符<<在谷歌c ++风格

[英]overload operator<< in google c++ style

I try to overload operator<< for my class so that it print member when I do std::cout << obj; 我尝试为我的类重载operator <<,以便在我执行std :: cout << obj时打印成员;

I see that the way to do this is 我知道这样做的方法是

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? 运算符重载的基本规则和习惯用法是什么?

However, I try to make my code conforms to Google C++ style guide https://google.github.io/styleguide/cppguide.html#Reference_Arguments 但是,我尝试使我的代码符合Google C ++风格指南https://google.github.io/styleguide/cppguide.html#Reference_Arguments

It says that passing the reference without const is not allowed except for the case that it is needed by convention such as swap(). 它表示不允许传递没有const的引用,除非按惯例需要它,例如swap()。 Is this overloading operator<< in the same category as swap()? 这个重载运算符<<与swap()在同一类别中吗? or there is a way to do something like 或者有办法做某事

std::ostream& operator<<(std::ostream* os, const T& obj)
                                     ^

? or something that does not take non-const reference as the input. 或者不以非const引用作为输入的东西。

If so, please teach me how to do that. 如果是这样,请教我如何做到这一点。 Thank you. 谢谢。

It says that passing the reference without const is not allowed except for the case that it is needed by convention 它表示不允许传递没有const的引用,除非按惯例需要它

Well, the stream is conventionally passed as a non-const reference into the stream insertion and extraction operators, so it would appear that the rule has allowed an exception for you. 好吧,流通常作为非const引用传递给流插入和提取操作符,因此看起来该规则允许您例外。 As such, defining the suggested overload should be conforming to the rule despite accepting a non-const reference argument. 因此,尽管接受非const引用参数,但定义建议的重载应该符合规则。

That said, I'm not an authority on what Google would consider as convention. 也就是说,我不是谷歌认为会议的权威。 If you work for Google, you should know whom to ask; 如果你在谷歌工作,你应该知道要问谁; If you don't then you don't need to get stressed over their style. 如果你不这样做,你就不需要对他们的风格感到压力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM