开发者

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

开发者 https://www.devze.com 2023-03-31 02:00 出处:网络
class two; class one { int a; public: one() { a = 8; } friend two; }; class two { public: two() { } two(one i) { cout << i.a;
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 开发者_如何学JAVA when compiled with Microsoft Visual C++ compiler.


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{};


Your code has:

friend two;

Which should be:

friend class two;
0

精彩评论

暂无评论...
验证码 换一张
取 消