2017-05-03 24 views
-1

這對其他人來說可能是常識,但令我驚訝的是,C++編譯器顯然按照它們出現在源文件中的順序聲明瞭Classes,這意味着在它的類出現在源文件中之前不能構造對象。我的問題是我怎樣纔能有一個類的成員函數返回一個對象之前,它的類聲明?C++中如何讓一個對象在聲明類之前返回一個對象?

Class Poo{ 
    Person Girate(int Magnitude){ 
     //Code Stuff 
     return person; 
    } 
}; 
Class Person{ 
    Poo Hydrate(int Direction){ 
     //more Code Stuff 
     return poo; 
    } 
}; 
+1

Dude - 這就是[forward declarations](https://en.wikipedia.org/wiki/Forward_declaration)是INVENTED的!你怎麼可以有無可爭議的徹斯特來解決你所問的問題?這就像說:「我口渴,但我不要求我喝任何東西」! – paulsm4

+0

「我需要」你爲什麼這麼認爲? –

+0

這是一個廢話問題 –

回答

1

你能做到這樣

class A;     // A forward declaration. A is an incomplete type at this point 

class B 
{ 
    A a();    // Okay to declare a function with incomplete return type 
         // but it would be an error to try defining it here 
}; 

class A 
{ 
    B b(); 
};      // A is a complete type now 

A B::a() { return A(); } // Can define B::a() now since the return type is complete 
B A::b() { return B(); } 

編輯:有沒有辦法做到這一點不向前聲明。

+0

我以爲OP(無論什麼原因)說他不想​​使用[forward declaration](https://en.wikipedia.org/wiki/Forward_declaration)?但你是對的 - 這是「解決方案」。 – paulsm4

+0

@ paulsm4我沒有看到編輯。 –

+1

@ paulsm4謝謝!這很尷尬,但由於某種原因,我忘了你可以在定義它之前聲明一個類,對於我造成的任何混淆抱歉,但是,這是我正在尋找的解決方案。 –