我煩惱undertanding以下錯誤:爲什麼在const方法中返回一個const X * const指針?
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;
}
爲什麼這是一個const X * const類型並且不能用作*常量 *?
由於該方法是一個常量方法,我的理解是它可以保護被修改的對象本身。那麼爲什麼編譯器試圖強制指向返回指針的指針的常量呢?
我一直無法找到使用堆棧溢出搜索引擎的這個問題的答案。
謝謝你的回答。
這裏是壓軸的代碼,我終於用,如果我能成爲一個人使用:
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;
}
與模板和簡單的數據結構只是在玩。 謝謝你的回答。
傳遞一個未初始化的指針到'IsValid' –
THX,試圖把重點放在錯誤 - 校正版本: 布爾的IsValid()const的 { const的BST ** previousNode =新常量BST *; * previousNode = nullptr; return this-> IsValid(previousNode); } bool IsValid(const BST ** previousNode)const –