【发布时间】:2009-12-07 09:52:41
【问题描述】:
我在尝试调用属于“形状”指针向量一部分的对象内的函数时遇到分段错误
我的问题出在这个函数上::
Point findIntersection(Point p, Point vecDir, int *status)
{
Point noPt;
for (int i = 0; i < shapes.size(); i++)
{
Point temp;
cout << "Shapes size" << shapes.size() << endl;
**SEGMENTATIONFAULT HERE >>>>>** bool intersect = shapes[0]->checkIntersect(p, vecDir, &temp);
if (intersect)
{
*status = 1; // Code 1 for intersecting the actual shape
return temp;
}
}
return noPt;
}
最初,我只添加一个形状:
void createScene()
{
image = QImage(width, height, 32); // 32 Bit
Sphere s(Point(0.0,0.0,-50.0), 40.0);
shapes.push_back(&s);
cout << shapes.size() <<endl;
}
所以我有一个全局的“形状”向量。 矢量形状;
我有一个班级形状
#include "Point.h"
#ifndef SHAPE_H
#define SHAPE_H
using namespace std;
class Shape
{
public:
Shape() {}
~Shape(){}
virtual bool checkIntersect(Point p, Point d, Point *temp) {}; // If intersects, return true else false.
virtual void printstuff() {};
};
#endif
还有一个 Sphere 类
#include "shape.h"
#include <math.h>
#include <algorithm>
using std::cout;
using std:: endl;
using std::min;
class Sphere : public Shape
{
public:
Point centerPt;
double radius;
Sphere(Point center, double rad)
{
centerPt = center;
radius = rad;
}
bool checkIntersect(Point p, Point vecDir, Point *temp)
{
cout << "Hi" << endl;
/*
Point _D = p - centerPt;
double a = Point :: dot(vecDir, vecDir);
double b = 2 * ( Point :: dot(vecDir, _D) );
double c = (Point :: dot(_D,_D)) - (radius * radius);
// Quadratic Equation
double tempNum = b * b - 4 * a * c;
if (tempNum < 0)
{
return false;
} else
{
double t1 = ( -b + sqrt(tempNum) ) / (2 * a);
double t2 = ( -b - sqrt(tempNum) ) / (2 * a);
double t;
if (t1 < 0 && t2 > 0) { t = t2; }
else if (t2 < 0 && t1 > 0) { t = t1; }
else if ( t1 < 0 && t2 < 0 ) { return false; }
else
{
t = min(t1, t2);
}
Point p1 = p + (vecDir * t);
if (p1.z > 0) // Above our camera
{
return false;
} else
{
temp = &p1;
return true;
}
}
*/
return false;
}
};
【问题讨论】:
-
显而易见的问题是如何填充“形状”向量?
-
我认为这不是问题,但 Shape 中的析构函数应该是虚拟的,
checkIntersect和printStuff可能应该是纯虚拟的(删除{}并替换为 @987654328 @) -
我尝试将其更改为 =0 仍然出现分段错误:(
-
还可以在向形状中添加元素的位置添加代码。
标签: c++