类型增强

C++是强类型语言

常变量类型 const

使用const修饰的变量称为常变量,C++中的常变量无法通过指针间接修改

1
2
3
const int a = 10;
int *p =&a;//此处你的编译器会显示类型不兼容错误
*p=20;

逻辑类型bool

C语言中没有逻辑类型,只能用非0为真,0为假。C++中增加了bool类型,true为 真,false为假

1
2
3
bool a = false;
bool b = true;
bool greater(int x,int y){return x > y;}//比较x是否大于y

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
namespace c
{
bool greater(int x, int y) { return x > y; }
}

bool main()
{
bool a = false;
bool b = true;
cout << c::greater(a, b);
}

枚举类型enum

在C++中,枚举变量只能通过枚举常量进行赋值

1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;
bool main()
{
enum temperature {WARM,COOL,HOT,dashabi};
enum temperature t = WARM;
cout << t <<' ';
t = dashabi;
cout << t;
}

错误示例:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;
bool main()
{
enum temperature {WARM,COOL,HOT,dashabi};
enum temperature t = WARM;
cout << t <<' ';
t = 2233;//此处错误
cout << t;
}

类型增强
https://niaoluo.top/2023/05/03/学习相关/C++/类型增强/
作者
熙恩
发布于
2023年5月3日
许可协议