已经有类似的问题,但它没有回答我的问题所以我会再次提问。
我有这个课程:
#ifndef _OBJECTS_H
#define _OBJECTS_H
#include "ray.h"
#include <cmath>
class Object {
public:
Vector3 position, color;
Object(Vector3 position, Vector3 color): position(position), color(color){};
virtual bool intersects() = 0;
};
class Sphere : public Object {
public:
float radius;
Sphere(Vector3 center, float radius, Vector3 color): Object(center, color), radius(radius){};
using Object::intersects;
bool intersects(const Ray& ray, float& t);
};
#endif
我需要拥有std::vector
个对象并遍历它:
for(Object s:objects) {
float t;
if (s.intersects(ray, t)) {
//do something
}
}
当我将intersects()
声明为pure virtual
时,它会告诉我我无法遍历虚拟类,如果我将其声明为virtual
那么它会告诉我相交没有实施。我做错了什么?
答案 0 :(得分:1)
作为(根据定义),您无法创建抽象类的实例,std::vector<>
不能包含抽象类的实例。您需要更改容器以包含指针。然后指针类型可以是指向抽象类的指针。