将值分配给动态分配的整数
Assign value to dynamically allocated integer
更新:
感谢大家帮助理解这一点!
我尝试运行这个:
#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;
作为声明,因此作为指向给定类型的指针,但找不到指向的类型,因此生成错误。相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 在c++中使用动态分配的问题
- 使用递归模板动态分配的多维数组
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 访问动态分配列表中的元素
- 为什么 std::equal_to会导致动态分配?
- 调用析构函数以释放动态分配的内存
- 动态分配Q_Property变量
- 在 C++ 中搜索动态分配的数组中的出现次数
- 动态分配的聊天数组打印缺失的数据和空
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 使用动态分配将 char* 复制到另一个字符**
- 使用指针在存在特征库的情况下动态分配 c++ 中的矩阵
- 将值分配给动态分配的整数
- 整数的动态分配
- 动态分配 2D 整数数组
- 动态分配一个新的整数数组
- 仅存储一个整数的指针的静态与动态分配