C++ 重载决议

标签 c++ inheritance

我想使用继承来根据对象在层次结构中的位置以不同的方式处理对象

( similar to this C# question )

假设您构建了一个 Shape 对象的层次结构,例如:

class Shape {} ;
class Sphere : public Shape {} ;
class Triangle : public Shape {} ; ...

然后为 Ray 类配备如下方法:

class Ray
{
    Intersection intersects( const Sphere * s ) ;
    Intersection intersects( const Triangle * t ) ;
};

您存储各种类型的各种 Shape* 数组并调用

vector<Shape*> shapes ; ...
//foreach shape..
Intersection int = ray.intersects( shapes[ i ] )

但是你得到了编译错误

错误 C2664:“Intersection Ray::intersects(const Sphere *) const”:无法将参数 1 从“Shape *const”转换为“const Sphere *”

你做错了什么?

反过来是唯一的方法,用

class Shape
{
    virtual Intersection intersects( const Ray* ray )=0 ;
} ;

然后每个类覆盖相交?然后调用

//foreach shape..
Intersection int = shapes[i]->intersects( ray ) ;

你能按照我展示的第一种方式做还是永远做不到?

最佳答案

你必须反过来做。重载决议发生在编译时,当您调用它的类型是 Shape* 时。

关于C++ 重载决议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6316955/

相关文章:

c++ - 将 "this"传递给线程 C++

c++ - 为什么当窗口在 win32 上失去焦点时,覆盖的非客户区显示默认值?

c++ - 是否有其他订单的平方根函数?

c++ - 是否有可能从基类函数 "inherit"派生函数?

c++ - 如果类使用虚拟继承,为什么对象大小会增加?

c# - 从基类的静态方法获取派生类类型

通过模板对unsigned int的C++限制

c++ - 无法使用 MinGW 链接到 SDL2 函数

c++ - 二进制补码表示

c++ - 当有多个派生类时,如何使用基类指针访问派生类的函数成员?