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

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

    This compiles, I assume without testing that it also works. Note the use of parentheses:

    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;
        return rhs;
    }
    
    int main() {}
    

    As Alexander mentions, though, your question doesn't explain why the operator isn't in namespace NAME. Either way it can be called as 1.0 * some_A_instance. So you may be creating needless trouble for yourself.

提交回复
热议问题