2012-05-22 49 views
0

爲什麼我不能在StateA中使l->set(new StateB);? (這條線在下面評論)類param編譯錯誤

它說:

main.cpp: In member function ‘virtual void StateA::writeName(Lap*, char*)’: 
main.cpp:19:4: error: invalid use of incomplete type ‘struct Lap’ 
main.cpp:3:7: error: forward declaration of ‘struct Lap’ 

,但我不解決這個:(

#include <stdio.h> 

class Lap; 
class State; 
class StateB; 
class StateA; 

class State { public: 
    virtual void writeName(Lap *l, char *str) = 0; 
}; 
class StateB : public State { public: 
    void writeName(Lap *l, char *str) { 
     printf("%s B\n", str); 
    } 
}; 
class StateA : public State { public: 
    void writeName(Lap *l, char *str) { 
     printf("%s A\n", str); 
     //l->set(new StateB); 
    } 
}; 
class Lap { public: 
    State *ss; 
    Lap(){ 
     printf("[Lap]\n"); 
     set(new StateA); 
    } 

    void set(State *s){ 
     ss = s; 
    } 

    void writeName(char *str){ 
     ss->writeName(this, str); 
    } 
}; 

int main() 
{ 
    printf("\n\n"); 

    Lap lap; 
    lap.writeName((char*)"Fulano"); 
    lap.writeName((char*)"Fulano"); 

    printf("\n\n"); 
    return 0; 
} 
+0

您正在嘗試使用不完整類型的方法。前向聲明讓編譯器知道類存在。 – chris

+0

@JesseGood顯然,破碎的部分被註釋掉了。 –

+0

@JesseGood - g ++,嘗試取消註釋行// l-> set(new StateB);' – Fabricio

回答

3

的問題是,向前聲明僅

class Lap; 

告訴編譯器,這樣的類存在,並讓你聲明指向Lap,但它不給編譯器有足夠的信息來處理任何Lap方法調用。

因此,您需要在嘗試使用其方法之前聲明Lap完全

與您的代碼給出我們不能在一個文件中完成,因爲Lap確實new StateAStateA呼籲Lap的方法 - 循環依賴。

您需要將聲明至少一個(並且更好,全部)移動到頭文件並在需要時包含頭文件。然後,編譯器將知道類的全部接口細節,然後該類的定義嘗試使用另一個類中的方法。