问题描述
我想这样做:
class Derived;
class Base {
virtual Derived f() = 0;
};
class Derived : public Base {
};
当然这不起作用,因为我不能返回一个不完整的类型。但是我也不能在base之前定义Derived,因为我也不能继承一个不完整的类型。我认为我可以使用模板作为一种解决方法(使用Derived作为Base的模板参数),但它似乎是一个真的丑陋的方式做事情。可能有另一种方式吗?
Of course this doesn't work since I can't return an incomplete type. But neither can I define Derived before base, since I can't inherit from an incomplete type either. I figure that I could use templates as a workaround (using Derived as a template argument to Base), but it seems a really ugly way of doing things. Might there be another way?
细化:我在写一个raytracer,每个Shape类有一个函数,它返回其边界框。但是,我把BBox作为Shape的一个子类,所以我可以想象它。这是不好的设计吗?
Elaboration: I'm writing a raytracer, and each Shape class has a function which returns its bounding box. However, I've made the BBox a subclass of Shape, so I can visualize it. Is this bad design?
推荐答案
问题中的代码没有问题。
There's nothing wrong with the code in your question. This
class Derived;
class Base {
virtual Derived f() = 0;
};
class Derived : public Base {
virtual Derived f() {return Derived();}
};
应编译正常。然而,'Base :: f()'的调用者将需要看到'Derived'的定义。
should compile just fine. However, callers of 'Base::f()' will need to have seen the definition of 'Derived`.
这篇关于是否可能从C ++中的基类方法返回一个派生类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!