Home > front end >  Error with befriending a function in a namespace in C
Error with befriending a function in a namespace in C

Time:02-21

I've tried to befriend a function in a namespace but I don't know why there is an error:

Error C2653 'a': is not a class or namespace name

I've tried multiple times and I don't think it's a mistake on my part but take a look:

class plpl
{
private:
    int m;
public:
    plpl()
        : m(3) {}

    friend void a::abc();
};

namespace a {
    void abc();
    void abc()
    {
        plpl p;
        std::cout << p.m << std::endl;
    }
}

I use Visual Studio 2019. I don't know what to do, please help.

CodePudding user response:

As suggested in comments, you need to forward declare the namespace a and the function abc, as shown below.

#include <iostream>

namespace a {
    void abc();
}

class plpl {
private:
    int m;
public:
    plpl() : m(3) {}

    friend void a::abc();
};

namespace a {
    void abc() {
        plpl p;
        std::cout << p.m << std::endl;
    }
}
  • Related