代码之家  ›  专栏  ›  技术社区  ›  Lawhatre

“::out”尚未声明[重复]

c++
  •  0
  • Lawhatre  · 技术社区  · 5 年前

    以下是代码

    #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";                                                                                                                 
          |              ^~~          
    

    EDIT:我原以为它会打印变量 out 其值为11(类似 nonlocal 在python中),但我得到了错误。我该怎么解决这个问题?

    1 回复  |  直到 5 年前
        1
  •  2
  •   Hassan    5 年前

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

    #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;
    }