将指针作为参数传递给引用时的 C++ 指针转换

标签 c++ pointers dynamic-cast

我很好奇,是:

bool State::operator<(const State* S)
{
  return this->operator<(*dynamic_cast<const State *>(S));
}

与以下内容完全相同:

bool State::operator<(const State* S)
{
  return this->operator<(*(S));
}

供引用this->operator<被调用的是:

bool State::operator<(const State& S)
{
  return this->reward < S.reward ? true : false;
}

哪一个更“正确”并且类型安全/可靠使用,或者有什么实际区别吗?

最佳答案

不,第一个将指针强制转换为自身,这实际上并没有执行任何操作,然后调用 const State* 重载,这会导致无限循环。在需要在运行时向下转换之前,您不需要 dynamic_cast — 这里没有向下转换,所以

return this->operator<(*S);

这是唯一要做的事情。

关于将指针作为参数传递给引用时的 C++ 指针转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6668106/

相关文章:

c - 初始化、构造结构并将其转换为字节数组会导致未对齐

c++ - 在 C 和 C++ 中通过指针访问结构

c++ - 如何在我的 C++ 代码中避免 dynamic_cast?

c++ - c++ 的最佳 instanceof 解决方法

c++ - 在不向模型添加代码的情况下对模型添加操作

C 指针未正确分配

c++ - 我想通过使用字符串数据类型而不是 char 类型来获得多行

C++ 映射唯一类并从值中提取子类

c++ - 如何制作像 R f<void(int)>(args...) 这样的模板函数

c++ - 在 CUDA 中合并读/写