恒美微站
首页
关于我们
建站服务
主题模板
案例展示
资讯中心
联系我们
C++ - 变量
首页
资讯中心
/
C++ - 变量
C++ - 变量
发布时间:2026/10/14 3:57:58
一.什么是变量存在内存中可以修改的量叫做变量变量有许多类型整型浮点型布尔型等等。变量也可以分为全局变量和局部变量前者可以在全文使用后者只能在特定的区域使用。二.变量的定义int x{10}注意在C中定义一个变量一定要赋给它具体的值否则编译器直接报错。三.变量的强制转换(想要转换成的类型变量名。代码演示#include iostream using namespace std; int main() { //定义一个int类型的变量x //如果不给他初始化值那这个值不确定,新版本编译器打印时直接报错。 int y; int x{ 100 }; cout 变量x的值为 100 endl; //通过变量前加符号获取变量的内存地址 //简单的强制转换 cout 变量x的内存地址 (long long)x endl; int z{ 200 }; cout 变量z的内存地址 z endl; cout int x的内存大小 sizeof(x) endl; long long bight{ 0 }; cout long long bight 内存大小 sizeof(bight) endl; return 0; }四.变量的算数运算变量的算数运算支持变量和字面量也支持自增和自减运算。代码演示#include iostream using namespace std; //全局变量 //作用域在不做声明的情况下在本文都可以访问。 //生命周期:main函数执行结束后释放空间。 int gx{ 0 }; int main() { cout gx gx endl; //局部变量 //作用域在定义变量所属的{}内部 //从变量定义开始到}结束 int py{ 50 }; cout py py endl; //运行时常量 const int cx{ 100 }; cout cx cx endl; //cx 200;//修改编译报错 constexpr int cex{ 300 }; cout cex cex endl; int t1 10; const int cx2{ t1 10 };//执行时常量可以用变量初始化 cout cx2 cx2 endl; //constexpr int cex2{t1 * 10};//无法用变量初始化编译时常量必须在编译时就知道值 //一般情况下用编译时常量涉及参数传递时用执行时常量。 return 0; }四.常量分类1.const int{x} - 运行时常量 - 可以用变量初始化2.constexpr int{x} - 编译时常量 - 不能用变量初始化代码#include iostream using namespace std; //全局变量 //作用域在不做声明的情况下在本文都可以访问。 //生命周期:main函数执行结束后释放空间。 int gx{ 0 }; int main() { cout gx gx endl; //局部变量 //作用域在定义变量所属的{}内部 //从变量定义开始到}结束 int py{ 50 }; cout py py endl; //运行时常量 const int cx{ 100 }; cout cx cx endl; //cx 200;//修改编译报错 constexpr int cex{ 300 }; cout cex cex endl; int t1 10; const int cx2{ t1 10 };//执行时常量可以用变量初始化 cout cx2 cx2 endl; //constexpr int cex2{t1 * 10};//无法用变量初始化编译时常量必须在编译时就知道值 //一般情况下用编译时常量涉及参数传递时用执行时常量。 return 0; }五.auto1.什么是auto?auto是C11的新特性是一个类型推导的关键字编译器根据初始化表达式自动推断变量的类型。2.代码演示#include iostream using namespace std; int main() { auto a1 10; auto d1 9.; auto f1 8.f; const int cex{ 10 }; auto acex cex;//auto推导常量会变成普通变量。 //constexpr auto c1 cex; - 编译常量不能用普通常量赋值。 const auto c2 a1; auto a3{ 11.3 }; auto a4 14LL; auto a5 (int)d1;//auto也支持强制转换 return 0; }