运算符重载和名称空间 [英] Operator overloading and namespaces
问题描述
可能重复:
非成员运算符重载应放在何处? >
Possible Duplicate:
Where should non-member operator overloads be placed?
在SO上浏览时,我经常发现涉及超载/定义std::ostream& operator<<(std::ostream& os, const Foo& foo)
或Foo operator+(const Foo& l, const Foo& r)
的问题或答案.
While browsing on SO, I often find questions or answer that involves overloading/defining a std::ostream& operator<<(std::ostream& os, const Foo& foo)
or a Foo operator+(const Foo& l, const Foo& r)
.
虽然我知道如何以及何时(不)编写这些运算符,但我对namespace
感到困惑.
While I know how and when (not) to write these operators, I'm confused about the namespace
thing.
如果我有以下课程:
namespace bar
{
class Foo {};
}
我应该在哪个namespace
中编写不同的运算符定义?
In which namespace
should I write the different operator definitions ?
// Should it be this
namespace bar
{
std::ostream& operator<<(std::ostream& os, const Foo& foo);
}
// Or this ?
namespace std
{
ostream& operator<<(ostream& os, const bar::Foo& foo);
}
// Or this ?
std::ostream& operator<<(std::ostream& os, const bar::Foo& foo);
operator+
也适用相同的问题.那么,这里的优良作法是什么?为什么?
The same question applies for the operator+
. So, what is the good practice here and why ?
推荐答案
它应位于bar
命名空间中.您必须考虑由什么构成类的接口,并将它们分组在一起.
It should be in the bar
namespace. You must consider what makes up the interface for the class, and group those together.
类描述了一组数据以及对该数据进行操作的功能."您的自由功能在Foo
上运行,因此它是Foo
的一部分.应该在名称空间bar
中将其与Foo
分组.
"A class describes a set of data along with the functions that operate on that data." Your free function operates on a Foo
, therefore it is part of Foo
. It should be grouped with Foo
in the namespace bar
.
依赖于参数的查找(即ADL)将找到该功能.
Argument-dependent lookup, or ADL, will find the function.
我们也知道我们应该首选非朋友非成员功能.通常,这意味着您的类将具有其定义和成员函数,紧随其后的是对类进行操作的自由函数.
We also know that we should prefer non-friend non-member functions. What this means is that, in general, your classes will have their definition and member functions, followed immediately by free functions which operate on the class.
这篇关于运算符重载和名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!