2012-05-13 93 views
2

我想創建一個具有子類「圓形」,「三角形」,「矩形」的父類「形狀」。父類擁有x pos,y pos和填充顏色或所有「形狀」,然後每個子類都擁有特定於該形狀的信息。有人會介意查看我的代碼,並看看爲什麼即時通訊錯誤「形狀沒有成員'setRadius'」當試圖設置對象數組中的半徑...動畫子類對象的數組

P.S.現在我只有孩子課「圈子」,直到我得到它的工作。然後我會添加其他兩個類。另外,如果有人在我的代碼中看到任何其他錯誤,我將不勝感激他們被指出。

在此先感謝

#include <allegro.h> 
#include <cstdlib> 

using namespace std; 

#define scrX 640 
#define scrY 400 
#define WHITE makecol(255,255,255) 
#define GRAY makecol(60,60,60) 
#define BLUE makecol(17,30,214) 

int random(int low, int high); 

const int numCircles = random(1,50); 

class Shape{ 
    public: 
     Shape(){x = scrX/2; y = scrY/2; fill = WHITE;} 
    protected: 
     int x, y, fill;  
}; 
class Circle : public Shape{ 
    public: 
     Circle(){radius = 0;} 
     Circle(int r){radius = r;} 
     void setRadius(int r){radius = r;} 
    protected: 
     int radius; 
}; 
int main() 
{ 
    // Program Initialization 
    allegro_init(); 
    install_keyboard(); 
    set_color_depth(32); 
    set_gfx_mode(GFX_AUTODETECT_WINDOWED, scrX, scrY, 0, 0); 

    // Create and clear the buffer for initial use 
    BITMAP *buffer = create_bitmap(scrX, scrY); 
    clear_to_color(buffer, GRAY); 

    // Set title and create label text in window 
    set_window_title("Bouncing Balls Ver 1.0"); 
    textout_ex(buffer, font, "Bouncing Balls Ver 1.0", 10, 20, WHITE, GRAY); 

    // Draw a background box 
    rectfill(buffer, 50, 50, scrX-50, scrY-50, BLUE); 

    // Create circles 
    Shape **GCir; 
    GCir = new Shape *[numCircles]; 
    for(int i=0;i<numCircles;i++){ 
     GCir[i] = new Circle; 
     GCir[i]->setRadius(random(1,25)); // THIS IS THE ERROR   
    } 

    while(!key[KEY_ESC]){ 
    blit(buffer, screen, 0, 0, 0, 0, scrX, scrY); 
    } 

    destroy_bitmap(buffer); 

    return 0; 
} 
END_OF_MAIN(); 
int random(int low, int high) 
{ 
    return rand() % (high - low) + low; 
} 

回答

0

編譯器說。您有一組形狀,您可以在其上嘗試調用僅爲圓形定義的setRadius。您只能調用形狀方法而無需將Shape poonter投射到圓形。

+0

我還沒有學會在課堂上還沒有鑄造,所以我不知道那是什麼或什麼呢? :)介意解釋我可以如何解決這個問題......希望你能看到我試圖做什麼... basicall使用快板,有多個形狀「彈跳」在屏幕上。一旦我的圈子工作,我可以得到其他形狀的工作。 – AGSperry

+0

告訴編譯器威脅到另一種類型(在mohaps'answer中顯示的語法)稱爲cast。有關詳情,請參閱http://en.wikibooks.org/wiki/C%2B%2B_Programming/Programming_Languages/C%2B%2B/Code/Statements/Variables/Type_Casting。 – dbrank0

1

錘修復:

GCir[i]->setRadius(random(1,25)); 

應改爲

((Circle*)GCir[i])->setRadius(random(1,25)); 

更深層次的問題:

您需要的BaseClass

虛析更好的方式來做到這一點是在Circle類構造函數中取半徑。 然後使用Shape :: draw()作爲虛函數來指定形狀繪製或實現Shape :: getType(),並在合適的投射後使用開關外殼來確定繪製邏輯。

2

類型的GCir[i]Shape*Shape類不具有setRadius方法,Circle一樣。所以,無論是Circle對象調用setRadius之前將其分配給GCir[i]或只是構建Circle用適當半徑:GCir[i] = new Circle(random(1,25));