This question already has answers here:
can't use structure in global scope
                                
                                    (2个答案)
                                
                        
                                去年关闭。
            
                    
为什么我不能像在python中那样重新分配全局变量int x?但是如果我把它放在功能上工作正常吗?

#include<iostream>
using namespace std;

int x = 30;
x = 40;

int main() {
    cout << x;
    system("pause");
    return 0;
};


谢谢,我是C ++新手

最佳答案

在C ++的全局范围内,您根本不分配变量。您只能初始化它们。语句x=40是没有意义的,因为在分配将要发生时尚未定义。

可能让您感到困惑的是,初始化C ++变量的一种方法看起来很像赋值。您可以分辨出两者之间的差异,因为使用=进行初始化是在声明的上下文中进行的,因此类型名称位于变量名称之前。

如果未将全局变量声明为const,则可以为它们赋新值,但这必须在语句块内进行---即在某种函数内。 main将用于此示例。

#include<iostream>
using namespace std;

int x = 30; // this is static initialization

int main()
{
  cout << x <<  '\n`;
  x = 40; // this is an assignment
  cout << "Now it's "  << x <<  '\n';
  cin.ignore(1);
  return 0;
};

关于c++ - 如何重新分配全局变量C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52124412/

10-11 22:09
查看更多