我一直在努力理解为什么我不能从该方法返回字符串指针。我需要从此方法返回一个指针,而不仅仅是返回一个字符串,因为它是链表分配的一部分。我该怎么办?
以下是方法:
std::string* lookupRec(Node* currentNode, std::string key)
{
if (currentNode != nullptr)
{
// If key == nodes key then that nodes item will be returned
if (currentNode->key == key)
{
// ERROR: cannot convert from 'string' to 'string *'
return currentNode->item;
}
else
{
return lookupRec(currentNode->ptrNext, key);
}
}
return nullptr;
}
答案 0 :(得分:2)
使用return ¤tNode->item;
。如果没有&
,编译器将尝试复制字符串并返回副本。使用&
时,字符串的地址作为指针返回。请注意,这等于return &(currentNode->item);
,即&
自动引用整个表达式,而不仅仅是currentNode
(即->
优先于&
)。
答案 1 :(得分:1)
最好附上“节点”结构的实现。
如果Node.item的类型为std::string
,则可以使用:
return ¤tNode->item;
不仅仅是currentNode->item
。