我的最后一个问题是一团糟.我收到了错误的输出.
所以在这里我有我的主要内容:
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);
Run Code Online (Sandbox Code Playgroud)
其中shape是vector <Shape*>形状;
Shape *x = shapes[0];
cout << "Shine" << x->shine << endl;
Run Code Online (Sandbox Code Playgroud)
即使答案应为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;
}
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)
问题是你在派生类中重复你的变量声明.你不需要重新声明变量一样double shine,它们已经在Shape,在派生类中Sphere.由于Sphere继承自Shape,所有公共成员变量都会Shape自动继承Sphere,并且不需要重新声明.重新定义它们将导致两个不同的成员变量,即Sphere::shine完全不同的变量Shape::shine.
因此,当您为一个值分配一个值Sphere::shine,然后使用Sphere基类Shape指针访问一个实例时,其值shine将不会是您所期望的.