2017-09-29 35 views
0

我有兩個cpp文件,每個文件都包含它們自己的類。在我的main.c文件中,我創建了這些類的全局聲明。我得到一個錯誤在我First.cppSecond.cppF_methodS_method,我嘗試引用全球類的實例裏面:C++外部錯誤

In member function 'void First::F_method()': error: invalid use of incomplete type 'class Second' note: forward declaration of 'class Second'

任何幫助將非常感謝!

MAIN.C

#include "First.h" 
#include "Second.h" 
#include "Global.h" 

First one; 
Second two; 


int main() 
{ 

    while(1){ 
     one.F_method(); 
     two.S_method(); 
    } 

} 

Global.h

extern class First one; 

extern class Second two; 

First.cpp

#include "First.h" 
#include <iostream> 
#include "Global.h" 

using namespace std; 

First::First() 
{ 
    //Constructor 
} 


void First::F_method() 
{ 
    std::cout << two.S_Var << std::endl; 
} 

First.h

#ifndef First_h 
#define First_h 


class First 
{ 
public: 
    First(); 

    void F_method(); 


    int F_Var = 66; 
}; 
#endif 

Second.cpp

#include "Second.h" 
#include <iostream> 
#include "Global.h" 

using namespace std; 

Second::Second() 
{ 
    //Constructor 
} 


void Second::S_method() 
{ 
    std::cout << one.F_Var << std::endl; 
} 

Second.h

#ifndef Second_h 
#define Second_h 


class Second 
{ 
public: 
    Second(); 

    void S_method(); 


    int S_Var = 12; 
}; 
#endif 
+0

你會得到什麼錯誤? – NathanOliver

+0

在成員函數'void First :: F_method()'中:錯誤:使用不完整的類'class Second'注意:'class Second'的前向聲明 – PanCy

+2

您需要在第二個中添加'#include「First.h」' .cpp和First.cpp中的#include「Second.h」。 –

回答

0

當使用First::F_method()two.S_Var,你沒有的Second完整定義。同樣,在Second::S_method()中使用one.F_Var時,您沒有First的完整定義。

您需要在Second.cpp中添加#include "First.h",在First.cpp中添加#include "Second.h"