2011-08-28 46 views
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(); 
} 

我越来越从开发 - C++这样的错误:如何解决“声明朋友时必须使用类”错误?

a class-key must be used when declaring a friend 

但是,当使用Microsoft Visual C++编译器编译运行正常。

+2

呃,请你能修正格式!我试过了,但太难了。 –

+1

请你可以修复你的空白。 –

+0

请注意,不要使用Dev-C++,它已经过时了。 – Griwes

回答

12

你需要

friend class two; 

,而不是

friend two; 

而且,你也不需要前瞻性声明的单独的类,因为朋友声明本身就是一个宣言。你甚至可以这样做:

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

class two{}; 
+1

thanxx的帮助,但我没有得到与Visual C++编译器错误 –

+3

@ desprado07:嗯,因为许多编译器不完全严格的这个规则(即类或结构体的字在朋友声明中)。然而,它按照11.4的标准要求。 [另一个问题]的接受答案(http://stackoverflow.com/questions/656948/a-class-key-must-be-declared-when-declaring-a-friend)可能会对你有所帮助。 –

+5

它允许在C++ 11中省略 –

5

您的代码有:

friend two; 

这应该是:

friend class two;