gpt4 book ai didi

c++ - 为什么在这里使用 static_cast 而不是 dynamic_cast?

转载 作者:太空狗 更新时间:2023-10-29 19:49:51 24 4
gpt4 key购买 nike

我从《更有效的 C++》一书中复制了以下文本。

第 31 条:关于多个对象使函数成为虚函数。

class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };

最常见的双重分派(dispatch)方法通过 if-then-elses 链将我们带回到无情的虚函数模拟世界。在这个严酷的世界中,我们首先发现 otherObject 的真实类型,然后针对所有可能性对其进行测试:

void SpaceShip::collide(GameObject& otherObject)
{
const type_info& objectType = typeid(otherObject);

if (objectType == typeid(SpaceShip)) {
SpaceShip& ss = static_cast<SpaceShip&>(otherObject);

process a SpaceShip-SpaceShip collision;

}
else if (objectType == typeid(SpaceStation)) {
SpaceStation& ss =
static_cast<SpaceStation&>(otherObject);

process a SpaceShip-SpaceStation collision;

}
...
}

问题是:

Q1> 为什么我们在这里使用 static_cast 而不是明显的 dynamic_cast?

Q2>‖在这种情况下它们是否相同?

谢谢

//已更新//

其实我对问题2更感兴趣。

例如,

class base {};
class subclass : public base {};

base *pSubClass = new subclass;

subclass *pSubClass1 = static_cast<subClass*> (pSubClass);

//虽然我知道我们应该在这里使用 dynamic_cast,但在这种情况下 static_cast 是否正确地完成了工作?

最佳答案

作为记录,这是执行此操作的惯用方法:

void SpaceShip::collide(GameObject& otherObject)
{
if (SpaceShip* ss = dynamic_cast<SpaceShip*>(&otherObject)) {
// process a SpaceShip-SpaceShip collision;
}
else if (SpaceStation* ss = dynamic_cast<SpaceStation*>(&otherObject)) {
// process a SpaceShip-SpaceStation collision;
}

// ...
}

它更短,表现出相同的性能特征,而且最重要的是,它是惯用的 C++,不会让其他程序员抓耳挠腮,想知道有什么意义。


EDIT(响应 OP 的编辑):

是的,这是定义明确的行为。这是 C++03 标准的内容,§5.2.9/8:

An rvalue of type “pointer to cv1 B”, where B is a class type, can be converted to an rvalue of type “pointer to cv2 D”, where D is a class derived from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists, cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is not a virtual base class of D. The null pointer value is converted to the null pointer value of the destination type. If the rvalue of type “pointer to cv1 B” points to a B that is actually a sub-object of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the result of the cast is undefined.

关于c++ - 为什么在这里使用 static_cast 而不是 dynamic_cast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6025466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com