2011-04-29 352 views
0

我對於使用C++的類和麪向對象方面相當陌生,並且在標題中得到錯誤。錯誤:''之前的預期初始值設定項。'令牌

我正在使用SDL編寫俄羅斯方塊遊戲。

我有shapes.h類定義

class shape 
{ 
public: 
    SDL_Surface *colour; 
    int rotation1[4][4]; 
    int rotation2[4][4]; 
    int rotation3[4][4]; 
    int rotation4[4][4]; 

    bool load(); 
    void move(); 

    shape(); 
}; 

和main.hi已包括shapes.h與

//Create shapes 
shape O, T, S, L, R, Z, I; 

定義的類的實例,我也有一個單獨的文件每個形狀如I.cpp,因爲每個形狀將具有不同的代碼,用於將圖像的塊顏色加載到SDL_Surface顏色和塊的不同旋轉的各種陣列上,因此我將其分成了每個塊的一個文件。

bool I.load() 
{ 
    //if loading the cyan square texture fails 
    if ((I.colour = surface::onLoad("../Textures/cyanSquare.png")) == NULL) 
    { 
     //print error 
     cout << "Unable to load cyanSquare.png"; 
     //return fail 
     return false; 
    } 

    I.rotation1 = {{7,7,7,7}, 
        {0,0,0,0}, 
        {0,0,0,0}, 
        {0,0,0,0}}; 
    I.rotation2 = {{0,0,7,0}, 
        {0,0,7,0}, 
        {0,0,7,0}, 
        {0,0,7,0}}; 
    I.rotation3 = {{7,7,7,7}, 
        {0,0,0,0}, 
        {0,0,0,0}, 
        {0,0,0,0}}; 
    I.rotation4 = {{0,0,7,0}, 
        {0,0,7,0}, 
        {0,0,7,0}, 
        {0,0,7,0}}; 

    return true; 
} 

當我嘗試編譯此(使用GCC)。報道線的錯誤:在I.cpp我已經包括main.h並試圖設置負載函數餘如下

I.cpp的3:

error: expected initializer before '.' token 

我完全不知道這意味着什麼,也不可能找到使用這個錯誤代碼谷歌搜索的東西,所以任何幫助,將不勝感激。

+2

它可能是放下編譯器並拿起[一本好書]的時候(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – 2011-04-29 16:28:22

回答

2
bool I.load() 

不應該是 bool shape::load()

我只是一個'shape'類型的實例。如何在函數實現中使用'I',因爲它對'I'實例一無所知!

你可能想這樣做: 1.添加帶參數的構建指定實例圖片:

class shape 
{ 
public: 
//.... 

    shape(const char* pImagePath); 
private: 
    const char* m_pImagePath; 
}; 

和落實構造爲:

shape::shape(const char* image_path) : m_pImagePath(pImagePath) {} 

你的負荷( )然後可以實施爲:

bool shape::load() 
{ 
    //if loading the cyan square texture fails 
    if ((colour = surface::onLoad(m_pImagePath)) == NULL) 
    { 
     cout << "Unable to load cyanSquare.png"; 
     return false; 
    } 

    rotation1 = {{7,7,7,7}, 
       {0,0,0,0}, 
       {0,0,0,0}, 
       {0,0,0,0}}; 
    rotation2 = {{0,0,7,0}, 
       {0,0,7,0}, 
       {0,0,7,0}, 
       {0,0,7,0}}; 
    rotation3 = {{7,7,7,7}, 
       {0,0,0,0}, 
       {0,0,0,0}, 
       {0,0,0,0}}; 
    rotation4 = {{0,0,7,0}, 
       {0,0,7,0}, 
       {0,0,7,0}, 
       {0,0,7,0}}; 

    return true; 
} 

創建實例'I'爲fo如下:

shape I("../Textures/cyanSquare.png"); 
+0

我認爲這樣做是可行的,因此不可能爲類的每個實例指定不同的函數,因爲您可以看到它們每個都有不同的數組和不同的紋理。如果我聽起來很荒謬,我很抱歉,我以前從未使用過課程。 – FrogInABox 2011-04-29 16:25:57

+0

我已經使用了你的方法,除了創建實例'I'之外,它似乎都能正常工作 - 我在這一行上得到了兩個錯誤: '預期的標識符在字符串常量之前'和 '預期的','或'.. '在字符串常量之前' – FrogInABox 2011-04-29 16:47:23

4

這是無效的C++。 I是一個變量;您無法爲特定變量定義成員函數(bool I.load())。也許你的意思是bool shape::load()

相關問題