2009-12-08 66 views
0

我最後的問題是一團糟。我收到錯誤的輸出。關於指針和對象的問題

所以在這裏我有我的主:

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 shineExp = 3.0; 
Sphere *s = new Sphere(Point(0.0,0.0,-5), 100.0, amb, difCoef, spec, shineExp); 
shapes.push_back(s); 

凡形狀是矢量<形狀*>形狀;

Shape *x = shapes[0]; 
cout << "Shine" << x->shine << endl; 

打印出零即使答案應該是3.0。

以下是我的課:

#include "shape.h" 
class Sphere : public Shape 
{ 
    public: 
    Point centerPt; 
    double radius; 
    Color ambient; 
    Color dif; 
    Color spec; 
    double shine; 

    Sphere(Point center, double rad, Color amb, Color difCoef, Color specu, double shineVal) 
    { 
     centerPt = center; 
     radius = rad; 
     ambient = amb; 
     dif = difCoef; 
     spec = specu; 
     shine = shineVal; 
    } 

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; 

}; 

回答

6

的問題是,你重複你的變量聲明在派生類中。在派生類Sphere中,您不需要重新聲明變量double shine,這些變量已在Shape中。由於Sphere繼承自Shape,所以Shape中的所有公共成員變量都會自動繼承Sphere,不需要重新聲明。重新聲明它們將導致兩個不同的成員變量,即Sphere::shine是與Shape::shine完全不同的變量。

因此,當你把值賦給Sphere::shine,再後來用基類指針Shape訪問Sphere一個實例中,shine值不會是你所期望的。

+0

謝謝,這樣比過去後一個更好的答案shine成員由於我的瘋狂*******問題:d – 2009-12-08 22:24:26

1

Sphere的每個實例都有兩個變量,稱爲shine。一個在派生類中,另一個在基類中。

Sphere構造函數初始化派生Sphere::shine,但x->shine訪問的基類變量,因爲x具有類型「指針Shape」。成員變量沒有任何「虛擬」行爲。

我幾乎可以肯定,你想要的是保持基類Shape中的公共變量,而不是在派生類中重新聲明相同名稱和類型的成員變量。您只應聲明派生類中的派生類唯一的屬性(例如centerPtradius對於Sphere)。

1

你不應該重新定義Sphere