如何解决"class must be used when declaring a friend"错误?

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

本文关键字:when used declaring 错误 friend be must 何解决 解决 class      更新时间:2023-10-16
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();
}

我从dev - c++得到这个错误:

a class-key must be used when declaring a friend

但在Microsoft Visual c++编译器下运行良好

你需要

 friend class two;

代替

 friend two;

同样,您不需要单独向前声明您的类,因为朋友声明本身就是一个声明。你甚至可以这样做:

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

你的代码有:

friend two;

应该是:

friend class two;