bool类型
- 取值位true(逻辑真)和false(逻辑假)
- 可以当作整数使用(true=1,false=0)
- 其他类型转为布尔值是,非零值转为true,零值转为false
#include <iostream>
using namespace std; //引入命名空间
int main(void)
{
bool result;
result = true;
cout<<result<<endl; //1
result = false;
cout<<result<<endl; //0
result = 100;
cout<<result<<endl; //1
result = -100;
cout<<result<<endl; //1
return 0;
}
const限定符
- const称为标识符常量,因为标识符常量的声明和使用形式很像变量,也称为常变量
- 常变量在定义时必须初始化,且初始化后不能再被赋值
#include <iostream>
using namespace std;
int main(void)
{
//const int a; error,常量必须初始化
const int a = 100;
//a = 200; error,常量不能重新赋值
int b = 33;
const int * p; //const在*左边,表示*p为常量,不能更改*p指向的内容
p = &b;
//*p = 200; error,常量不能重新赋值
//int * const p2; error,p2常量必须初始化
int * const p2 = &b;
int c = 100;
//p2 = &c; error,常量不能重新赋值
*p2 = 200;
return 0;
}
const与#define
- const定义有类型,且分配内存,#define没有
- const会进行类型安全检查,#define只是在预编译阶段进行宏替换
- const定义的常变量的作用域为该变量的作用域范围,#define定义的常变量作用域为它的定义点到程序结束,可以用#undef取消
- 定义常量还可以用enum
#include <iostream>
using namespace std;
#define STR(a) #a
#define CAT(a,b) a##b
int main(void)
{
int xy = 50;
cout<<STR(abcd)<<endl; //#abcd <=> "abcd"
cout<<CAT(x,y)<<endl; //x##y <=> xy
return 0;
}
结构体对齐
- 在对齐的地址上访问数据块,可以提高性能
- 第一个数据存放在offset为0的位置
- 其他成员对齐值min( sizeof(member),#pragma pack (n) )的整数倍
- 结构体大小为各个成员中最大对齐数的整数倍
#include <stdio.h>
#include <iostream>
using namespace std;
#pragma pack(4) //设为4个字节读取为12
struct Test
{
char a;
double b;
};
#pragma pack()
int main(void)
{
Test test;
printf("%p\n",&test);
printf("%p\n",&test.a); //&test <=> &test.a
cout<<sizeof(Test)<<endl; //默认16,取sizeof(double)=8的整数倍
return 0;
}
,域运算符::
- 用于对与局部变量同名的全局变量进行访问
- 用于表示类的成员
#include <iostream>
using namespace std;
int var = 100;
int main(void)
{
int var = 50;
cout<<var<<endl; //50
cout<<::var<<endl; //100
return 0;
}