c++ - 为什么这会在 const 方法中返回一个 const X* const 指针?

标签 c++ pointers

我在理解以下错误时遇到了麻烦:

Error 1 error C2440: '=' : cannot convert from 'const X<...> *const ' to 'X<...> *const '

我正在尝试使用指向 const 指针的指针在树遍历期间跟踪节点:

bool IsValid() const
  {
    X* const* previousNode = new X*;
    return this->IsValid(previousNode);
  }

  bool IsValid(X* const* previousNode) const
  {
    ...
    if (!*previousNode)
      *previousNode = this; // Error
    ...

    return true;
  }

为什么 thisconst X* const 类型,不能用作 *Const * ?

由于该方法是const方法,我的理解是它保护对象本身不被修改。那么,为什么编译器会尝试强制指向返回 this 的指针的指针的常量性?

我一直无法使用堆栈溢出的搜索引擎找到这个问题的答案。

感谢您的回答。

如果我可以为某人使用,这是我最终使用的结局代码:

bool IsValid() const
  {
    std::unique_ptr<const BST*> previousNode = std::unique_ptr<const BST*>(new const BST*);
    *previousNode = nullptr;
    return this->IsValid(prevNode);
  }

bool IsValid(std::unique_ptr<const BST*>& previousNode) const
{
  // Recurse on left child without breaking if not failing
  if (this->leftChild &&!this->leftChild->IsValid(previousNode))
    return false;

  // First node retrieved - assign
  if (!*previousNode)
    *previousNode = this;
  // Previous data does not compare well to the current one - BST not valid
  else if (!Compare()((*previousNode)->data, this->data))
    return false;

  // Set current node
  *previousNode = this;

  // Recurse on right child
  if (this->rightChild && !this->rightChild->IsValid(previousNode))
    return false;

  return true;
}

只是玩玩模板和简单的数据结构。 感谢您的回答。

最佳答案

让我们从简单的开始:

  • const X* 是一个指向常量 X 的指针
  • a const X* const 是指向常量 X 的常量指针
  • 一个const X* const*是一个指向常量的指针指向一个常量

回到你的问题:

  • X* const* previousNode 是指向 X 的常量指针的指针
  • 所以 *previousNode 是指向 X 的常量指针
  • 但是 *previousNode = ... 试图为这个常量指针分配一些东西。不可能,指针是常量!

关于c++ - 为什么这会在 const 方法中返回一个 const X* const 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38191673/

相关文章:

c++ - 将字符串分配给指针数组

c - C 中的指针、结构和函数

C++ Eigen初始化静态矩阵

c++ - 如何修复 strlen 的 'Conditional jump or move depends on uninitialised value(s)' valgrind 错误?

c# - 从托管代码调用 native 函数

c - 访问struct的指针成员数据

c++ - 复制 Boost 标记图

c# - 从 64 位 .NET 代码调试 64 位 C++ - 如何?

c - 小型 C 程序 basic.returning 一个指针

c - 如何使用带有结构数组的指针?