开发者

Trouble with objects and Pointers

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;

};

When it prints out shine, i get a value of zero? Why is that?


I think object slicing occures (since you'r using a Shape object and assigning to it). What you would want to do in order to preserve polymorphism is use a pointer or a reference. In this case I would use a pointer:

Shape *x = shapes[0];

If shapes is an odd container which does de-reference (this is what i understand from your code) then I would use a reference:

Shape &x = shapes[0];

You could use a const reference, but it isnt mandatory here since your object is not a temporary one by any means.

Btw, hasn't anybody told you globals are a bad practice?


This code cannot be compiling. If you have defined a container for Shape* as is implied by the lines

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

Then, you could not be retrieving a Shape from shapes as in

Shape x = shapes[0];


Assuming Shape is an base class of Sphere and others, you should not make a copy of it. Currently, you are (probably) slicing the object which is actually a Sphere by making a copy of its Shape base part.

Taking a pointer or a reference to the Shape object, as others have suggested, should solve your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜