c++ - 当返回类型声明为 ListNode 时我们可以返回 false*
问题描述
我不是 C++ 程序员,所以给定这个函数(你可能认识它),当返回类型声明为 ListNode* 时返回 false 是否有效?
编译器抱怨,但寻找解决方案似乎是 IDE 受到了指责。我只是想了解是否允许这样做,因此 IDE 有问题,或者这实际上是一个错误。
如果有帮助,这是 Arduino 代码,我使用的是 IDE 版本 1.8.11
template<typename T>
ListNode<T>* LinkedList<T>::getNode(int index) {
int _pos = 0;
ListNode<T>* current = root;
// Check if the node trying to get is
// immediatly AFTER the previous got one
if(isCached && lastIndexGot <= index) {
_pos = lastIndexGot;
current = lastNodeGot;
}
while(_pos < index && current) {
current = current->next;
_pos++;
}
// Check if the object index got is the same as the required
if(_pos == index) {
isCached = true;
lastIndexGot = index;
lastNodeGot = current;
return current;
}
return false;
}
编译器报告:
cannot convert bool the ListNode<Device*>*
这是调用此函数的示例;
template<typename T>
bool LinkedList<T>::add(int index, T _t) {
if(index >= _size)
return add(_t);
if(index == 0)
return unshift(_t);
ListNode<T> *tmp = new ListNode<T>(),
*_prev = getNode(index-1);
tmp->data = _t;
tmp->next = _prev->next;
_prev->next = tmp;
_size++;
isCached = false;
return true;
}
同样,不是 C++ 程序员,我不理解这段代码。看起来*_prev
分配了 的结果getNode(index-1)
,这可能是错误的。然后看起来它试图访问_prev->next
. 但会_prev
是假的,还是*_prev
假的?我不明白。
解决方案
你真的不应该在return false;
那里。你想要做的是return nullptr;
或者return NULL;
如果nullptr
不可用。过去这只是一个警告的原因可能是您过去使用了较旧的 c++ 标准。在我的系统上,您会得到以下不同 c++ 标准的信息:
代码:
int* test() {
return false;
}
int main() {
test();
}
输出:
$ clang++ -std=c++98 test.cpp -Wall -Wextra
test.cpp:2:12: warning: initialization of pointer of type 'int *' to null from a constant boolean expression [-Wbool-conversion]
return false;
^~~~~
1 warning generated.
$ clang++ -std=c++03 test.cpp -Wall -Wextra
test.cpp:2:12: warning: initialization of pointer of type 'int *' to null from a constant boolean expression [-Wbool-conversion]
return false;
^~~~~
1 warning generated.
$ clang++ -std=c++11 test.cpp -Wall -Wextra
test.cpp:2:12: error: cannot initialize return object of type 'int *' with an rvalue of type 'bool'
return false;
^~~~~
1 error generated.
在 C++11 标准中似乎对此有所改变。我不确定那里到底发生了什么变化,我从 C++11 知道的关于转换的唯一变化是显式运算符,也许其他人可以在这方面说些什么。
推荐阅读
- string - 将字符串的第一个字母转换为大写的快速函数?
- swift - 如何在 Firebase 中对数据进行排序?
- java - Spring Data Rest:导出非数据自定义 CrudRepository
- c# - 在运行时将数据绑定到 XAML
- javascript - 反应本地文件夹中的本地调用动态图像
- django - [DJANGO][GUNICORN] 不允许操作
- java - 验证是否存在唯一字符串的组合
- c# - 访问 ListboxItem 中的控件
- python - 为什么 2 * x * x 在 Python 3.x 中比 2 * ( x * x ) 快,对于整数?
- javascript - .Net 服务器上类似浏览器的体验