非成员运算符超载在哪里应该放置? [英] Where should non-member operator overloads be placed?

查看:108
本文介绍了非成员运算符超载在哪里应该放置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的类重载运算符< 。我应该将这个重载的定义添加到 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 ) {}

?感谢您的回复。

推荐答案

您应该将运算符重载到与您的类相同的命名空间中。

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.

这篇关于非成员运算符超载在哪里应该放置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆