gpt4 book ai didi

c++ - 在成员函数中,是否可以暂时将参数 "parent"解释为子参数?

转载 作者:行者123 更新时间:2023-11-28 06:11:37 24 4
gpt4 key购买 nike

bool  COLL::Rectangle::collides (const Collider & other) const noexcept
{
bool boolean;
switch (other.type)
{
case RECTANGLE: // i have defined a enum type to do introspection
//i am sure that what will reach this part will be a Rectangle, which inherits from Collider.

boolean = (contains (other.origin) || contains (other.origin.first));
break;
case CIRCLE:
break;
default:
break;
}
return boolean;
}

我的问题是:我可以对我的编译器说:“嘿,对于这几行,该对象将被视为一个矩形。”也许动态或静态 Actor ?我不太了解。

如果将 Rectangle 转换为 Rectangle,会有问题吗?

非常感谢。

最佳答案

如果您绝对确定 other 在代码中的那一点是一个 Rectangle,那么您可以安全地static_cast 它。

case RECTANGLE:
Rectangle& rect = static_cast<Rectangle&>(other);
//...
break;

另一种可能更简洁的解决方案是通过 visitor pattern 使用双分派(dispatch).例如,您可以定义 collide(Rectangle&)collide(Circle&) 函数,然后像 other.collide(*this);。这样做将消除对类型枚举的需要。

关于c++ - 在成员函数中,是否可以暂时将参数 "parent"解释为子参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31162288/

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