C/C++:类型别名(typedef、using)、类型说明符(auto、decltype)

一、类型别名

1、typedef

(1)定义普通类型

#include <iostream>
using namespace std;

typedef unsigned char u8, *u8p;

int main()
{
	u8 c = 'c';          // unsigned char
	u8p pc = &c;         // unsigned char *
	cout << *pc << endl;

	return 0;
}

(2)定义函数类型

#include <iostream>
using namespace std;

/*
void fun(int a)
{

}
*/

typedef void (*fun)(int);

int main()
{
    

	return 0;
}

2、using

#include <iostream>
using namespace std;

using u32 = unsigned int;
using u32p = unsigned int*;

int main()
{
	u32 a = 10;          // unsigned int
	u32p pa = &a;         // unsigned int *
	cout << *pa << endl;

	return 0;
}

二、类型说明符(类型指示符)

1、auto

       auto 通过初值 来推算 变量的类型,auto 变量必须有初值。

       对于引用,取引用所绑定的类型。

       对于顶层const,会被忽略掉。

auto a = 10, *b = &a, &c = a;       // 整形,默认int,2147483647
int a = 10, *b = &a;
auto c = b;             // int*
int a = 10, &b = a;
auto c = b;             // int, 引用所绑定的对象的类型
const int a = 10;
auto b = a;             // int, 会忽略顶层 const
auto c = &a;            // const int *, 指向 const int 的指针,此时是底层 const

       如果想要顶层const,则需要手动添加const

const int a = 10;
auto b = a;             // int, 会忽略顶层 const

const auto c = a;       // const int

       如果想要引用,则需要手动添加引用符号&

int a = 10, &b = a;
auto c = b;             // int, 引用所绑定的对象的类型

auto &d = b;            // int &, 主动加引用

2、decltype

       decltype 返回操作数、表达式的数据类型,只分析类型,并不实际计算表达式或者调用。

(1)非表达式

decltype(fun()) a;    // a 的类型就是 fun() 返回的类型
const int a = 10;
decltype(a) b;        // const int
const int a = 10, &b = a;
decltype(b) c = a;        // const int &, 引用,需要初始化

(2)表达式

       如果表达式返回的是一个左值,则返回引用类型。

       如果表达式返回一个右值,则返回普通类型。

int a = 10;
decltype((a)) b = a;        // int &, 引用,左值,加括号
int a = 10, b = 20;
decltype(a=b) c = a;        // int &, 引用,左值,赋值
int a = 10, *b = &a;
decltype(*b) c = a;        // int &, 引用,左值,解引用
int a = 10, &b = a;
decltype(a+0) c = a;        // int, 右值
decltype(b+0) d = a;        // int, 右值

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值