[英]Type conversion error when returning pointer
我想返回一個指針(或對一個指針的引用)而不是對我的值的引用。 但我不斷收到轉換錯誤。
我嘗試將返回類型更改為 Node* 但它不將其識別為已知類型,因為 Node 是一個結構。
使用模板時,我很難清楚地理解這些轉換錯誤。 我還沒有找到這些轉換的明確答案。
error: cannot convert ‘TreeAVL<int>::Node*’ to ‘const int*’ in return
template<class T>
const T* TreeAVL<T>::find(Node* node, const T& element) const {
if (node == nullptr)
return nullptr;
if (element == node->value)
return &(node->value);
//return &(node); <<<< what I want to return if found.
...
}
要了解轉換錯誤,
error: cannot convert ‘TreeAVL<int>::Node*’ to ‘const int*’ in return
您必須查看產生此錯誤的模板的定義,類似於:
// A function returning const T*
template<class T>
const T* TreeAVL<T>::find(Node* node, const T& element) const {
// OK, any T* can be a nullptr:
if (node == nullptr)
return nullptr;
// But here the return value is a TreeAVL<T>::Node*, which is not
// necessarily convertible to any T*
if (element == node->value)
return node;
// ...
}
因此,一旦將此模板與不兼容的T
(例如示例中的int
)一起使用,就會出現錯誤。 如果您想返回指向節點的指針,則必須聲明 function 這樣做,並且其返回語句必須與之兼容。
此外,如果您想避免繁瑣的類型名,您還可以使用const auto*
,或者將定義內聯並將其指定為const Node*
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.