将值分配给动态分配的整数

Assign value to dynamically allocated integer

本文关键字:整数 动态分配 分配      更新时间:2023-10-16

更新:
感谢大家帮助理解这一点!

我尝试运行这个:

#include <iostream>
int* x = new int;
*x = 5;
int main()
{
}


我收到以下错误:

1>------ Build started: Project: learnCpp, Configuration: Debug Win32 ------
1>learnCpp.cpp
1>C:UsersDaniesourcereposlearnCpplearnCpp.cpp(4,6): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>C:UsersDaniesourcereposlearnCpplearnCpp.cpp(4,2): error C2374: 'x': redefinition; multiple initialization
1>C:UsersDaniesourcereposlearnCpplearnCpp.cpp(3): message : see declaration of 'x'
1>C:UsersDaniesourcereposlearnCpplearnCpp.cpp(4,7): error C2440: 'initializing': cannot convert from 'int' to 'int *'
1>C:UsersDaniesourcereposlearnCpplearnCpp.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 的外部块作用域中。

您尝试执行的操作在全局范围内是不可能的。

如果您需要这样做,请尝试按如下方式初始化:

// good practice 
namespace
{
    int* x = new int(5);
}
int main()
{
    // You can later modify in function scope
    *x = 10;
}

除声明之外,不能有任何范围之外的语句(为简单起见,请考虑括号内的任何范围(。所以,编译器正在尝试解释

*x = 5;

作为声明,因此作为指向给定类型的指针,但找不到指向的类型,因此生成错误。