Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve "class must be used when declaring a friend" error?

class two;
class one
{
    int a;
    public:
        one()
        {
            a = 8;
        }
    friend two;
};

class two
{
    public:
        two() { }
        two(one i)
        {
            cout << i.a;
        }
};

int main()
{
    one o;
    two t(o);
    getch();
}

I'm getting this error from Dev-C++:

a class-key must be used when declaring a friend

But it runs fine when compiled with Microsoft Visual C++ compiler.

like image 614
shubhendu mahajan Avatar asked Dec 03 '22 07:12

shubhendu mahajan


2 Answers

You need

 friend class two;

instead of

 friend two;

Also, you don't need to forward-declare your class separately, because a friend-declaration is itself a declaration. You could even do this:

//no forward-declaration of two
class one
{
   friend class two;
   two* mem;
};

class two{};
like image 172
Armen Tsirunyan Avatar answered Dec 21 '22 23:12

Armen Tsirunyan


Your code has:

friend two;

Which should be:

friend class two;
like image 30
SoapBox Avatar answered Dec 21 '22 23:12

SoapBox