一.什么是变量?
存在内存中可以修改的量叫做变量,变量有许多类型,整型,浮点型,布尔型等等。变量也可以分为全局变量和局部变量,前者可以在全文使用,后者只能在特定的区域使用。
二.变量的定义
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;
}
五.auto
1.什么是auto?
auto是C++11的新特性,是一个类型推导的关键字,编译器根据初始化表达式自动推断变量的类型。
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;
}