返回指针时输入转换错误
ID喜欢返回指针(或引用一个),而不是对我的值的引用。但是我一直遇到转换错误。
我尝试将返回类型更改为节点*,但由于节点是struct,因此它并未将其识别为已知类型。
使用模板时,我很难清楚地了解这些转换误差。我还没有对这些转换找到明确的答案。
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.
...
}
Id like to return a pointer(or reference to one) instead of a reference to my value. But I keep getting conversion errors.
I tried changing the return type to Node* but it doesnt recognize it as a known type since Node is a struct.
I'm having a hard time understanding these conversion erros clearly when using templates. I havent found a clear answer to these conversions yet.
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.
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要了解转换错误,
您必须查看产生此错误的模板的定义,这将是类似的:
因此,一旦使用此模板与不兼容的
t
使用此模板,就会遇到错误,例如示例中的int
。如果您想将指针返回到节点,则必须声明函数必须这样做,并且其返回语句必须与此兼容。另外,如果要避免使用繁琐的打字名称,也可以使用
const auto*
,或对内联定义并将其指定为const node*
。To understand the conversion error,
You have to look at the definition of the template that produces this error, which would be something like:
So you get an error as soon as you use this template with an incompatible
T
, such asint
in your example. If you want to return a pointer to a node instead, the function must be declared to do so, and its return statements must all be compatible with that.Also, if you want to avoid the cumbersome typename, you can also use
const auto*
, or make the definition inline and specify it asconst Node*
.