我在理解以下错误时遇到了麻烦:
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;
}
为什么 this 是 const 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/