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

后端 未结 4 1554
抹茶落季
抹茶落季 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:31

    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.

提交回复
热议问题