Where should non-member operator overloads be placed?(非成员运算符重载应该放在哪里?)
问题描述
我想为我的班级重载 operator<<
.我应该将此重载定义添加到 std
命名空间吗?(因为 ostream 运算符<<
是 std
命名空间的一部分)还是应该将它留在全局命名空间中?
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?
简而言之:
class MyClass {
};
namespace std {
ostream& operator<< ( ostream& Ostr, const MyClass& MyType ) {}
}
或
class MyClass {
};
std::ostream& operator<< ( std::ostream& Ostr, const MyClass& MyType ) {}
哪个更合适,为什么?提前感谢您的回复.
Which is more appropriate and why? Thanks in advance for your responses.
推荐答案
您应该将运算符重载放在与您的类相同的命名空间中.
You should put the operator overload in the same namespace as your class.
这将允许在重载解析期间使用依赖于参数的查找找到运算符(实际上,由于 ostream
在命名空间 std
中,重载重载也会如果你把它放在命名空间 std
中就可以找到,但没有理由这样做).
This will allow the operator to be found during overload resolution using argument-dependent lookup (well, actually, since ostream
is in namespace std
, the overload overload would also be found if you put it in namespace std
, but there is no reason to do that).
从良好设计实践的角度来看,运算符重载更多是类接口的一部分,而不是 ostream
的接口,因此它与您的类属于同一命名空间(另请参阅Herb Sutter 的 命名空间和接口原则).
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).
从编写符合标准的可移植代码的角度来看,您不能将运算符重载放入命名空间std
.虽然您可以将用户定义实体的模板特化添加到命名空间 std
,但您不能添加额外的函数重载.
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 namespace std
, you can't add additional function overloads.
这篇关于非成员运算符重载应该放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:非成员运算符重载应该放在哪里?


基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01