非成员运算符重载应该放在哪里?
我想为我的类重载operator<<
。我应该将此重载定义添加到 std
命名空间吗? (因为 ostream 运算符<<
是 std
命名空间的一部分)或者我应该将其保留在全局命名空间中?
简而言之:
class MyClass {
};
namespace std {
ostream& operator<< ( ostream& Ostr, const MyClass& MyType ) {}
}
OR
class MyClass {
};
std::ostream& operator<< ( std::ostream& Ostr, const MyClass& MyType ) {}
哪个更合适,为什么?预先感谢您的回复。
I want to overload operator<<
for my class. Should I add this overloaded definition to the std
namespace? (since the ostream operator<<
is part of the std
namespace) Or should I just leave it in the global namespace?
In short:
class MyClass {
};
namespace std {
ostream& operator<< ( ostream& Ostr, const MyClass& MyType ) {}
}
OR
class MyClass {
};
std::ostream& operator<< ( std::ostream& Ostr, const MyClass& MyType ) {}
Which is more appropriate and why? Thanks in advance for your responses.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该将运算符重载放在与您的类相同的命名空间中。
这将允许在重载解析期间使用参数相关的查找来找到运算符(实际上,由于
ostream
位于命名空间std
中,因此如果你把它放在命名空间std
中,但没有理由这样做)。从良好设计实践的角度来看,运算符重载更多地是您的类接口的一部分,而不是
ostream
的接口,因此它与您的类属于同一命名空间(另请参阅 Herb Sutter 的 < a href="http://www.gotw.ca/publications/mill08.htm" rel="noreferrer">命名空间和接口原理)。从编写符合标准和可移植代码的角度来看,您不能将运算符重载放入命名空间
std
中。虽然您可以将用户定义实体的模板专业化添加到命名空间std
,但您无法添加其他函数重载。You should put the operator overload in the same namespace as your class.
This will allow the operator to be found during overload resolution using argument-dependent lookup (well, actually, since
ostream
is in namespacestd
, the overload overload would also be found if you put it in namespacestd
, but there is no reason to do that).From the point of view of good design practices, the operator overload is more a part of your class's interface than the interface of
ostream
, so it belongs in the same namespace as your class (see also Herb Sutter's Namespaces and the Interface Principle).From the point of view of writing standards-compliant and portable code, you can't put the operator overload into namespace
std
. While you can add template specializations for user-defined entities to namespacestd
, you can't add additional function overloads.不要将其添加到
std
命名空间,而是将其放置在与您的类相同的命名空间中。命名空间的目的是防止冲突。标准说Don't add it to the
std
namespace, place it in the same namespace as your class. The purpose of a namespace is to prevent collisions. The standard says不要添加到标准命名空间。
原因:如果每个人都这样做,标准命名空间将会出现大量名称冲突,这违背了命名空间的目的。
您的目标是让您的班级成为“ostream-able”。它不需要位于标准名称空间中即可执行此操作。只要它位于您的类声明的任何名称空间中,就可以了。将其放在标准命名空间中是不好的做法。
Don't add to the standard namespace.
Reason : If everybody did this, the standard namespace would have heaps of name clashes, which defeats the purpose of a namespace.
Your objective is for your class to be "ostream-able". It does not need to be in the standard namespace to do that. As long as it is in whatever namepsace your class is declared in, you're fine. Putting it in the standard namespace would be bad practice.