How do I define friends in global namespace within another C++ namespace?

后端 未结 4 1561
抹茶落季
抹茶落季 2021-01-01 19:08

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 th

4条回答
  •  醉酒成梦
    2021-01-01 19:51

    It is possible - you can enclose the declarator in parentheses: friend A (::operator * (double lhs, const A& rhs));

    You also need to forward-declare both the class and the function.

    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) {
      //...
    }
    

    But I agree with Andreas that it would be better to define both in the same namespace if possible.

提交回复
热议问题