【问题标题】:'::out' has not been declared [duplicate]'::out' 尚未声明 [​​重复]
【发布时间】:2021-04-25 04:00:04
【问题描述】:

下面是代码

#include <iostream>

using namespace std;

int main()
{
    int x=5, y=6;
    int out = x + y;

    {
        int out= 89;
        cout << :: out << "\n";
    }

    cout << out;
}

为此我得到了

error: ‘::out’ has not been declared                                                  
   12 |   cout << :: out << "\n";                                                                                                                 
      |              ^~~          

编辑:我期待它打印值为 11 的变量 out(如 python 中的 nonlocal),但我得到了错误。我该如何解决这个问题?

【问题讨论】:

  • 在显示的代码中没有名为out 的全局变量。有两个局部变量都命名为out,两者都不能称为::out。您可以通过为不同的变量赋予不同的名称并删除 :: 来解决此问题
  • @IgorTandetnik,@songyanyao。感谢您指出。但是,如果我想访问外部块的 out 而不是内部块怎么办(例如 python 语言中的 nonlocal)。
  • 没有语法。只是给他们不同的名字。
  • 这里没有错误消息指出“范围解析运算符尚未声明”。您必须准确引用错误消息,这也意味着您必须准确阅读它们。这也有助于防止您草率下结论。
  • @AdityaSinghRathore。这真的很有帮助。

标签: c++


【解决方案1】:

没有全局变量out,你必须在main之外声明一个全局变量,或者你可以简单地去掉作用域解析运算符::并打印out的值

#include <iostream>
using namespace std;
int main()
{
    int x = 5, y = 6;
    int out = x + y;
    {
        int out = 89;
        cout << out << "\n";
    }
    cout << out;
}

如果要使用全局变量,请先更改名称

#include <iostream>
using namespace std;
int Globalout;
int main()
{
    int x = 5, y = 6;
    Globalout = x + y;
    {
        int Localout = 89;
        cout << Localout << "\n";
    }
    cout << ::Globalout;
}

【讨论】:

  • 这个答案是错误的。删除 :: 将仅打印当前范围。没有办法访问不是全局变量的外部范围。
  • 是的!我知道,但我们可以将 out 存储在具有不同名称的引用变量中。
  • 请删除您说的部分只需删除范围解析运算符 :: 并打印 out 的值。这是误导。它将打印当前范围out,即 89,而不是外部范围 out,即 11 以及问题所要求的内容。
  • 不得不说,C++中没有办法访问同名的外域局部变量。除了在内部变量之前给出不同的名称或创建对具有不同名称的外部变量的引用。
猜你喜欢
  • 2015-06-12
  • 2011-01-22
  • 2017-05-18
  • 2017-07-05
  • 2019-09-19
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多