简体   繁体   English

Visual C ++变量声明

[英]Visual C++ variable declarations

In my MainApp.XAML.h file within the namespace brackets, I have: 在命名空间括号内的MainApp.XAML.h文件中,我具有:

int food;
food = 0;

When I compile the code I get a couple of errors saying: 当我编译代码时,我得到几个错误:

Error C4430 missing type specifier - int assumed

and: 和:

Error C2086 'int MonsterFights::food': redefinition

but when I google how to declare a variable, it shows the same way as I am doing. 但是当我用谷歌搜索如何声明一个变量时,它显示的方式与我所做的相同。

Am I missing something? 我想念什么吗?

--EDIT-- - 编辑 -

So if I need to put my variables in my .cpp file, where abouts in the .cpp file do I put them? 因此,如果我需要将变量放在.cpp文件中,那么在.cpp文件中,abouts应该放在哪里?

Currently I have it here: 目前我在这里:

MainPage::MainPage()
{
    InitializeComponent();
}
int food = 5;

There are two problems here: 这里有两个问题:

  1. The first is that you have a variable definition in the header file. 首先是在头文件中有一个变量定义 That means the variable will be defined in every translation unit (roughly a source file with all included header files) where you include the header file. 这意味着将在包含头文件的每个翻译单元 (大约是包含所有头文件的源文件)中定义变量。

    You can only have one single definition of each variable, and should only have declarations in the header file. 每个变量只能有一个定义,并且头文件中只能有声明 Move the definition to a single source file, and have a declaration instead in the header file: 将定义移动到单个源文件,并在头文件中添加一个声明:

     extern int food; 
  2. The second problem is that you can't have general statements in the global scope or in namespace scope, only declarations and definitions. 第二个问题是,您不能在全局范围或命名空间范围中具有常规语句,而只能具有声明和定义。

    You solve this by changing your definition (the one you have in a source file) to initialize the variable: 您可以通过更改定义(源文件中的定义)以初始化变量来解决此问题:

     int food = 0; 

    Note that this initialization is not really needed for global variables. 请注意,对于全局变量,实际上并不需要此初始化。 The compiler will make sure that otherwise uninitialized global variables are suitable initialized to "zero", which for int variables means they will become 0 . 编译器将确保将未初始化的全局变量适当地初始化为“零”,这对于int变量意味着它们将变为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM