2013-02-27 29 views
-1

我在試圖建立一個射線追蹤器。我有一個名爲Shape的類,我將它擴展到Sphere類(以及其他形狀,如三角形)。形狀有方法我重寫此方法的方式有什麼問題?

virtual bool intersect(Ray) =0; 

所以我通過

class Sphere : public Shape{ 
public: 
    Sphere(){}; 
    bool intersect(Ray){/*code*/}; 
}; 

創建球體類我有我用它來創建形狀指針列表的主類。我創建一個球體指針並執行以下操作:

Sphere* sph = &Sphere(); 
shapes.emplace_front(sph); //shapes is a list of Shape pointers 

然後,當我想跟蹤在另一大類射線我做了以下內容:

for (std::list<Shape*>::iterator iter=shapes.begin(); iter != shapes.end(); ++iter) { 
    Shape* s = *iter; 
    bool hit = (*s).intersect(ray); 
} 

,但我得到的是我不能叫相交錯誤在虛擬類Shape上,儘管它應該是* s指向一個Sphere類型對象。我在做什麼錯誤的繼承?

回答

4

的一個問題是這樣的:

Sphere *sph = &Sphere(); 

它創建Sphere類型的臨時對象,存儲一個指針到該臨時,然後破壞臨時。結果是無稽之談。

它改成這樣:

Sphere *sph = new Sphere(); 

事情會好得多。

+0

謝謝,我認爲那樣做了。 – 2013-02-27 22:00:19