2017-03-01 35 views
0

我們可以在C++主程序之後定義struct嗎?當我們定義函數時,我們可以在主程序之前聲明函數,然後在主函數之後寫入函數定義。我想知道在定義結構時是否可以做類似的事情。謝謝。我們可以在C++的主函數之後定義結構嗎?

+7

你爲什麼不試試? – Netwave

+0

是的,你可以做到這一點。查找_forward聲明_。 –

+0

http://en.cppreference。com/w/cpp/language/class#Forward_declaration –

回答

4

我們可以在C++主程序之後定義struct嗎?

我推測你的意思是main函數。是的,我們可以在main函數之後定義類(包括結構)。一個演示:

int main(){} 
struct S{}; 

當我們定義函數,我們可以主程序之前聲明函數,然後寫主程序後,函數定義。我想知道在定義結構時是否可以做類似的事情。

同樣適用於類,您可以(向前)在函數之前聲明它們,並在之後定義。但是,不完整(已聲明但未定義)類的使用非常有限。您可以定義它們的指針和引用,但不能創建它們或調用任何成員函數。演示:

struct S;  // (forward) declaration of a class 
S* factory(); // (forward) declaration of a function 
int main(){ 
    S* s = factory(); // OK, no definition required 
    // s->foo();  // not OK, S is incomplete 
    // S s2;   // not OK 
} 
struct S{    // definition of a class 
    void foo();  // declaration of a member function 
}; 
S* factory() { 
    static S s;  // OK, S is complete 
    s.foo();   // OK, note how the member function can be called 
         // before it is defined, just like free functions 
    return &s; 
} 
void S::foo() {}  // definition of a member function 
3

編輯:正如評論中提到的@ user2079303,我錯誤地使用了術語「前向聲明」。我相應地更新了我的答案。

如果您只想存儲指向該結構的指針,則可以轉發聲明結構。但是,一旦定義了結構,您只能在該指針上調用方法。

#include <iostream> 

// forward declaration of struct 
struct S; 
// pointer can be defined after forward declaration 
S * s; 

void workOnSPointer(); 

int main() 
{ 
    workOnSPointer(); 
} 

// definition of struct 
struct S 
{ 
    S() : bar(42) {} 
    void foo() { std::cout << "bar is " << bar << "\n"; } 
    int bar; 
}; 

// methods can only be called after definition 
void workOnSPointer() 
{ 
    S * s = new S(); 
    s->foo(); 
    delete s; 
} 

您還可以前瞻性聲明中的結構定義結構的方法,而後來的定義這些方法。

#include <iostream> 

// incomplete definition of struct S 
// methods of the struct are only declared here 
struct S 
{ 
    S(); 
    void foo(); 
    int bar; 
}; 

int main() 
{ 
    S s; 
    s.foo(); 
} 

// definition of the struct's methods 
S::S() : bar(42) {} 
void S::foo() { std::cout << "bar is " << bar << "\n"; } 

這一定義與前瞻性聲明的方法是主要使用的標題(.h)文件。您可以在頭文件中定義結構,並將頭文件包含在使用該結構體的文件中。您的方法的定義進入源文件(.cpp)。適用於上面的代碼,這意味着:

文件S.h

struct S 
{ 
    S(); 
    void foo(); 
    int bar; 
}; 

文件S.cpp

#include "S.h" 
#include <iostream> 

S::S() : bar(42) {} 
void S::foo() { std::cout << "bar is " << bar << "\n"; } 

文件main.cpp

#include "S.h" 

int main() 
{ 
    S s; 
    s.foo(); 
} 

如果編譯S.cppmain.cpp,然後立在生成的目標文件中,您將獲得與開始時代碼相同的行爲。

+0

@ user2079303是對的,前向聲明可以用來定義指針。 –

+0

另一個正向聲明'struct'的示例:http://coliru.stacked-crooked.com/a/8789088991c57916 –

+2

'void main()'不正確,它應該是'int main()'。 – mch

相關問題