我一直试图摆脱此错误,但似乎没有任何效果。我正在使用OpenGL在Visual Studio 2012中的C ++中进行编码。在这里,我初始化rtScene
对象,此对象的默认构造函数读取一个文件并设置其他数据成员值。
当我调用函数SphereSet()
时,错误弹出,该函数使用数据成员的相应函数设置sphere的数据成员的值。
class rtPoint
{
friend class Sphere;
friend class rtScene;
private:
double xx,yy,zz;
public:
rtPoint():xx(0),yy(0),zz(0){cout<<"vi";};
void rtPointSet(double x,double y,double z)
{
xx=x;yy=y;zz=z;
//cout<<xx<<" "<<yy<<" "<<zz<<"\n";
}
void rtPointSet(rtPoint p)
{
xx=p.xx;
yy=p.yy;
zz=p.zz;
}
};
class Sphere
{
friend class rtScene;
private:
rtPoint center;
double radius;
color3 color;
Material surface;
public:
Sphere():center(),radius(1),color(),surface(){};
void SphereSet(double x,double y,double z,double r,
double rr,double gg,double bb,double Par,
double Pag,double Pab, double Pdr, double Pdg,
double Pdb,double Psr,double Psg,double Psb,double PhCo)
{
center.rtPointSet(x,y,z);
color.set(rr,gg,bb);
radius=r;
surface.MaterialSet(Par, Pag, Pab, Pdr, Pdg, Pdb, Psr, Psg, Psb, PhCo);
}
};
class rtScene
{
private:
Sphere *Sph_obj;
//Sphere Sph_obj[3];
int nS,nL;
rtCamera CAM;
rtLight *Lights;
public:
rtScene(char *fname)
{
FILE *fp;
fp=fopen(fname,"r");
double a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q;
char ch;
//.........read camera.........//
fscanf(fp,"%lf,%lf,%lf,%lf,%lf,%lf\n",&a,&b,&c,&d,&e,&f); // 6 values
this->CAM.rtCameraWindow(a,b,c,d,e,f);
fscanf(fp,"%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf\n",&a,&b,&c,&d,&e,&f,&g,&h,&i); // 9 values
this->CAM.rtCameraSet(a,b,c,d,e,f,g,h,i);
//.............................//
//.......read Lights.............//
fscanf(fp,"%c %d\n",&ch,&nL);
cout<<nL;
if(ch=='l')
{
this->Lights=new rtLight[nL];
for(int i=0;i<nL;i++)
{
fscanf(fp,"%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf\n",&a,&b,&c,&d,&e,&f,&g,&h,&i,&j,&k,&l); //12 values
this->Lights[i].rtLightSet(a,b,c,d,e,f,g,h,i,j,k,l);
}
}
//..............................//
//.....read spheres.............//
fscanf(fp,"%c %d\n",&ch,&nS);
cout<<nS;
if(ch=='s')
{
this->Sph_obj=new Sphere[nS];
//Sph_obj=(class Sphere *) malloc(sizeof(Sphere)*nS);
for(int i=0;i<nS;i++)
{
fscanf(fp,"%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf\n",&a,&b,&c,&d,&e,&f,&g,&h,&i,&j,&k,&l,&m,&n,&o,&p,&q);
this->Sph_obj[i].SphereSet(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q);
}
}
//.............................//
}
};
函数
rtPointSet
尝试为中心变量设置xx
,yy
,zz
值时,代码崩溃,给出错误“ ray tracer.exe中0x010A85FB的首次机会异常:0xC0000005:访问冲突写入位置0x709DF990”球体。 最佳答案
您正在覆盖循环变量。
for(int i=0;i<nS;i++) // Loop over 'i'
{
fscanf(fp, [...],&i,[...]); // Oops!
this->Sph_obj[i].SphereSet([...]; // Bang!
}
声明变量接近它们的使用并且不重新使用它们是一件好事-如果您在循环内声明了
a
.. q
,则编译器将为您捕获该错误。