2009-12-08 43 views
-1
vector < Shape* > shapes; 

void createScene() 
{ 

image = QImage(width, height, 32); // 32 Bit 
Color amb(0.1,0.1,0.1); 
Color difCoef(0.75,0.6,0.22); 
Color spec(0.5,0.5,0.5); 
double shine= 3.0; 
Sphere *s = new Sphere(Point(0.0,0.0,-5), 100.0, amb, difCoef, spec, shine); 
shapes.push_back(s); 

} 




int main(){ 

// initialize glut 
init(); 
createScene(); 
Shape *x = shapes[0]; 
cout << x->shine << endl; 
} 





class Shape 
{ 
public: 
Shape() {} 
~Shape(){} 
Color ambient; 
Color dif; 
Color spec; 
double shine; 
virtual bool checkIntersect(Point p, Point d, Point &temp) = 0; // If intersects, return true else false. 
virtual Point getNormal(Point intPt) = 0; // Get the normal at the point of intersection 
//virtual void printstuff() = 0; 

}; 

當它打印出光芒時,我得到一個零值?這是爲什麼?對象和指針的問題

+1

我認爲你需要提供更多一點你的代碼.... – retracile 2009-12-08 19:37:45

+4

你的形狀[]定義在哪裏? – 2009-12-08 19:38:30

+0

什麼庫是'Shape'?這是你設計的課程還是來自圖書館? – 2009-12-08 19:38:39

回答

2

我認爲object slicing發生(因爲你使用一個Shape對象並賦值給它)。爲了保留多態性,你想要做的是使用指針或引用。在這種情況下,我會用一個指針:

Shape *x = shapes[0]; 

如果形狀是一個奇怪的容器,它不會去參考(這是我從你的代碼理解),那麼我會用一個參考:

Shape &x = shapes[0]; 

你可以使用一個const引用,但這裏並不強制,因爲你的對象不是一個臨時的引用。

順便說一句,有沒有人告訴過你,全局變量是不好的做法?

0

假設Shape是Sphere等人的基類,你不應該複製它。目前,您可能(可能)通過複製其Shape形狀部分來複制實際上是Sphere的對象。

像其他人所說的那樣,對Shape對象的指針或引用應該可以解決您的問題。

2

此代碼無法編譯。如果您已經爲Shape*定義的一種容器,由線暗示

Sphere *s = new Sphere(Point(0.0,0.0,-5), 100.0, amb, difCoef, spec, shine); 
shapes.push_back(s); 

然後,你無法檢索從shapes一個Shape

Shape x = shapes[0]; 
+0

除非他使用公共繼承,並且意外地將他的Sphere實例切片到Shape實例中。 – 2009-12-08 19:47:47

+1

@Joe:「公共禁忌」與它有什麼關係?在第一種情況下,它是一個指針的容器,在第二個對象本身中。正如戴夫正確指出的那樣,OP的代碼沒有任何意義。 – AnT 2009-12-08 19:53:50

+0

+1:OP的代碼甚至不應該編譯爲以 – 2009-12-08 19:58:31