简体   繁体   English

我重写此方法的方式有什么问题?

[英]What is wrong with the way I'm overriding this method?

I'm trying to build a ray tracer. 我正在尝试构建光线追踪器。 I have a class called Shape which I'm extending to the class of Sphere (and other shapes as well, like triangles). 我有一个名为Shape的类,现在将其扩展到Sphere(以及其他形状,如三角形)类。 Shape has the method 形状有方法

virtual bool intersect(Ray) =0;

And so I create the Sphere class by 所以我通过创建Sphere类

class Sphere : public Shape{
public:
    Sphere(){};
    bool intersect(Ray){/*code*/};
};

I have a main class which I use to create a list of Shape pointers. 我有一个主类,用于创建Shape指针列表。 I create a Sphere pointer and do the following: 我创建一个Sphere指针并执行以下操作:

Sphere* sph = &Sphere();
shapes.emplace_front(sph); //shapes is a list of Shape pointers

Then when I want to trace the ray in another class I do the following: 然后,当我想在另一个类中追踪射线时,请执行以下操作:

for (std::list<Shape*>::iterator iter=shapes.begin(); iter != shapes.end(); ++iter) {
    Shape* s = *iter;
    bool hit = (*s).intersect(ray);
}

But I get the error that I cannot call intersect on a the virtual class Shape, even though it should be that *s points to a Sphere type object. 但是我得到一个错误,我不能调用在虚拟类Shape上相交,即使它* s指向Sphere类型对象也是如此。 What am I doing wrong with inheritance? 我在继承问题上做错了什么?

One problem is this: 一个问题是:

Sphere *sph = &Sphere();

It creates a temporary object of type Sphere , stores a pointer to that temporary, then destroys the temporary. 它创建Sphere类型的临时对象,存储指向该临时对象的指针,然后销毁该临时对象。 The result is nonsense. 结果是胡说八道。

Change it to this: 更改为此:

Sphere *sph = new Sphere();

things will work much better. 情况会好得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM