【问题标题】:C++ forget to declare variable type causes errorC++忘记声明变量类型导致错误
【发布时间】:2018-09-04 01:00:34
【问题描述】:

我很困惑为什么以下代码由于以下错误而无法编译:'rootLevel' was not declared in this scope

据我了解,struct NodeLevel 是在 class Solution 之前声明和定义的,这不是 Solution 类可以使用此类的充分条件吗?

谢谢!

struct NodeLevel{
    int level;
    BinaryTreeNode * node;
    NodeLevel(int val, BinaryTreeNode * x) : level(val), node(x) {}  
};

class Solution {
public:
    vector<vector<int>> levelOrder(BinaryTreeNode* root) {
        queue<NodeLevel> q;
        rootLevel = NodeLevel(0, root);
        q.push(rootLevel);

        /*
        do some stuff with the queue 
        */
    }
};

【问题讨论】:

  • NoteLevel rootLevel = NodeLevel(0, root);
  • 代码中有太多的小怪事。当我清理并获得minimal reproducible example 时,我已经本能地修复了这个错误。
  • rootLevel 的第一个用法是 rootLevel = NodeLevel(0, root); 。这不会将其声明为变量 - 如果声明了 rootLevel,它会使用它,但(与其他一些编程语言不同)不声明变量。要么将该行从 rootLevel = NodeLevel(0, root) 更改为 NodeLevel rootLevel = NodeLevel(0, root)(在 C++11 和更高版本中,这可以是 auto rootLevel = NodeLevel(0, root))或者(更简单地说,因为它明确避免创建对象然后复制它)NodeLevel rootLevel(0, root)
  • @user4581301 这是一个错字。我试图删除原来的注释行,但在那里遗漏了一个“/”。
  • @Peter 感谢您的详细回复!我对 C++ 不够熟悉,显然有时仍然忘记声明变量类型。感谢您发现这一点!

标签: c++ class scope


【解决方案1】:

编译器是正确的,你没有声明变量rootLevel

【讨论】:

  • 我认为,至少下一次,与其指出它是错误的(正如您从问题中看到的那样),请至少更正代码,而不仅仅是复制粘贴...
  • 好吧,如果您不了解意图,我认为您无法更正代码。我在问那个代码块的目的。
  • 尽管询问代码的目的是一种很好的做法,但它实际上比仅仅按照自己的方向前进要好。那应该是评论。此外,代码很简单,可以看出他只是缺少错误'rootLevel' was not declared in this scope 中所述的变量声明
  • 感谢您指出。我试图解决这个问题:leetcode.com/problems/binary-tree-level-order-traversal/…,这段代码是设置的一部分:-) 我省略了#include 语句和算法部分,以使问题更简单......
猜你喜欢
  • 2011-05-31
  • 2022-08-17
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 2019-11-05
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多