简体   繁体   中英

Friend operator in different namespace

Currently the following code is not working:

namespace inner
{
    struct Test
    {
        Test() : n(0) { }
        friend int ::operator+(const Test& a, const Test& b);
    private:
        int n;
    };
}

int operator+(const inner::Test& a, const inner::Test& b)
{
    return a.n + b.n;
}

and the error I get is

error: 'int operator+(const inner::Test&, const inner::Test&)' should have been declared inside '::'

         friend int ::operator+(const Test& a, const Test& b);

                                                            ^

I thought qualifing the namespace would fix the problem but it doesn't. What's a workaround?

A friend declaration can only introduce a name into the immediately surrounding namespace.

If you want to befriend a function in any other namespace, then you'll need to declare that function, in its namespace, before the friend declaration. As the error message says.

In this case, you probably want the operator to be in inner rather than the global namespace. Argument-dependent lookup will still find it in an expression like test_a + test_b , even if it's not otherwise in scope.

您必须在结构中使用运算符之前对其进行声明。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM