如何在另一个C ++名称空间的全局名称空间中定义好友? [英] How do I define friends in global namespace within another C++ namespace?
问题描述
我想在全局名称空间中定义一个二进制运算符.运营商 在另一个命名空间中定义的类上工作,并且运算符应获取 访问该类的私人成员.我的问题是我没有 在类定义中成为朋友时,知道如何确定该全局运算符的作用域.
I'd like to define a binary operator on in the global namespace. The operator works on a class that is defined in another namespace and the operator should get access to the private members of that class. The problem I have is that I don't know how to scope that global operator when making it a friend in the class definition.
我尝试过类似的事情:
namespace NAME
{
class A {
public:
friend A ::operator * (double lhs, const A& rhs);
private:
int private_var;
};
}
A operator * (double lhs, const A& rhs)
{
double x = rhs.private_var;
...
}
编译器(g ++ 4.4)不知道如何处理.看来这行
The compiler (g++ 4.4) didn't know what to do with it. It seems that the line
friend A ::operator * ()
被评估为类似(伪代码)
is evaluated as something like (pseudo-code)
(A::operator)
代替
(A) (::operator)
如果在运算符的声明中省略::,则可以编译,但是运算符位于名称空间NAME中,而不位于全局名称空间中.
If I leave out the :: in the declaration of the operator the compiling works but the operator is then in namespace NAME and not in the global namespace.
在这种情况下如何限定全局名称空间?
How can I qualify the global namespace in such a situation?
推荐答案
首先,请注意您的运算符声明缺少A的命名空间限定:
First, note that your operator declaration was lacking a namespace qualification for A:
NAME::A operator * (double lhs, const NAME::A& rhs)
然后决定性的诀窍是像您在伪代码"中所建议的那样,将括号添加到这样的朋友声明中
and then the decisive trick is to add parentheses to the friend declaration like this, just as you proposed in your "pseudo-code"
friend A (::operator *) (double lhs, const A& rhs);
要使其全部编译,则需要一些前向声明,以达到以下目的:
To make it all compile, you then need some forward declarations, arriving at this:
namespace NAME
{
class A;
}
NAME::A operator * (double lhs, const NAME::A& rhs);
namespace NAME
{
class A {
public:
friend A (::operator *) (double lhs, const A& rhs);
private:
int private_var;
};
}
NAME::A operator * (double lhs, const NAME::A& rhs)
{
double x = rhs.private_var;
}
但是,亚历山大是对的,您应该在与参数相同的名称空间中声明运算符.
Alexander is right, though -- you should probably declare the operator in the same namespace as its parameters.
这篇关于如何在另一个C ++名称空间的全局名称空间中定义好友?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!