【问题标题】:Can we return false when the return type is declared as a ListNode<T>*当返回类型声明为 ListNode<T>* 时我们可以返回 false
【发布时间】:2020-02-04 19:50:07
【问题描述】:

我不是 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-&gt;next。但是_prev 是假的,还是*_prev 是假的?没看懂。

【问题讨论】:

  • 如果你的函数返回一个ListNode&lt;T&gt;*return false;应该怎么做?
  • false 不是指针。也许您想返回NULL
  • arduinos 支持 C++11 吗?请求nullptr
  • @srayner 我猜它应该返回 nullptr 而不是 false。
  • 请在问题中包含编译器错误。如果编译器告诉你代码有问题,那么在所有情况下,99.9% 的情况是代码有问题

标签: c++ arduino


【解决方案1】:

你真的不应该在那里return false;。如果nullptr 不可用,您想要做的是return nullptr;return NULL;。过去这只是一个警告的原因可能是您过去使用了较旧的 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 中知道的关于转换的唯一变化是显式运算符,也许其他人可以在这方面说些什么。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2016-05-11
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多