运算符重载和命名空间
可能重复:
非成员运算符重载应该放在哪里? p>
在浏览 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
.
Argument-dependent lookup 或 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.
相关文章