2011-08-28 115 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; 
相關問題