4
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++ 编译器编译时运行良好。

4

2 回答 2

12

你需要

 friend class two;

代替

 friend two;

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

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

class two{};
于 2011-08-28T11:36:21.353 回答
5

您的代码有:

friend two;

应该是:

friend class two;
于 2011-08-28T11:37:12.943 回答