更新:
感谢大家帮助理解这一点!
我试着运行这个:
#include <iostream>
int* x = new int;
*x = 5;
int main()
{
}
我收到以下错误:
1>------ Build started: Project: learnCpp, Configuration: Debug Win32 ------
1>learnCpp.cpp
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,6): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,2): error C2374: 'x': redefinition; multiple initialization
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(3): message : see declaration of 'x'
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,7): error C2440: 'initializing': cannot convert from 'int' to 'int *'
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,4): message : Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
1>Done building project "learnCpp.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
但是,如果我在主函数中将值赋给 x,我不会收到任何错误。
像这样:
#include <iostream>
int* x = new int;
int main()
{
*x = 5;
}
怎么会?
最佳答案
在 C 的文件作用域中,您只能放置声明。您不能在文件范围内执行语句。这同样适用于 C++,您可以在命名空间中仅放置声明。
注意:在 C 中,声明不是语句,而在 C++ 中,声明是语句。然而,除了声明语句外,其他语句可能不会出现在 C++ 的命名空间中。还值得注意的是,在 C 中有一个 null 语句,但没有空声明。而在 C++ 中可能有一个空声明。
所以这个程序
#include <iostream>
int* x = new int;
*x = 5;
int main()
{
}
无效。
编译器的这些错误信息
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2374: 'x': redefinition; multiple initialization
message : see declaration of 'x'
意味着编译器试图将赋值语句解释为声明。
但是这个程序
#include <iostream>
int* x = new int;
int main()
{
*x = 5;
}
是正确的。在这个程序中,赋值语句出现在函数 main 的外部 block 范围内。
关于c++ - 为动态分配的整数赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59007041/