108.类型别名声明

发布时间 2023-07-18 12:07:04作者: CodeMagicianT

108.类型别名声明

在代码编辑过程中,为了书写省事或者更容易理解,通常会自定义别名,包括类型别名、方法别名等。在 C++ 中定义别名有以下几种方式。

1.#define

1.1概述

#define 是宏定义,作用就是将一个标识符定义为一个字符串,源程序中所有的该标识符均以指定的字符串代替,在预编译阶段执行。

1.2定义类型别名

#include "iostream"
using namespace std;

#define intPtr int * //定义一个 int * 指针类型
int main()
{
	intPtr x = new int(6);
	cout << x << " " << *x << endl;

	system("pause");
	return 0;
}

运行结果如下:

000001E23FB49AE0 6

宏定义仅进行文本替换,若连续定义变量,则可能和预期不符:

intPtr y, z;
//实际替换结果:int * y,z;

编译器中查看如下,变量y、z类型不一样:


1.3定义函数别名

#include "iostream"
using namespace std;

void func()
{
	cout << "hello " << endl;
}

#define PRINTHELLO func

int main()
{
	PRINTHELLO();

	system("pause");
	return 0;
}

运行结果如下:

hello
请按任意键继续.

2.typedef

2.1概述

typedef是用来申请类型别名的,本质是为数据类型起了一个别名,也相当于定义了一个新的类型。

2.2定义数据类型

#include "iostream"
using namespace std;

typedef int* IntPtr;
int main()
{
	IntPtr x = new int(6);
	cout << x << " " << *x << endl;

	system("pause");
	return 0;
}

2.3定义数组类型

typedef char mysize[10];
mysize m_array;

2.4定义结构体类型

typedef struct m_struct
{
	char c;
}s;

s m_struct;

2.5定义函数类型

#include "iostream"
using namespace std;

typedef int func(int a, int b);

int add(int a, int b)
{
	return a + b;
}

int sub(int a, int b)
{
	return a - b;
}

int main()
{
	func* calFunc;

	calFunc = add;
	cout << calFunc(4, 5) << endl;

	calFunc = sub;
	cout << calFunc(4, 5) << endl;

	system("pause");
	return 0;
}

但是使用 typedef 定义的函数类型定义的非指针变量不可以直接赋值:

typedef int func(int a,int b);
func  f = add;//出错

可用于函数声明:

#include "iostream"
using namespace std;

typedef int func(int a, int b);

func  add;//声明一个函数

int main()
{
	system("pause");
	return 0;
}
//函数定义
int add(int a, int b)
{
	return a + b;
}

2.6定义函数指针

#include "iostream"
using namespace std;

typedef int (*func)(int a, int b);

int add(int a, int b)
{
	return a + b;
}

int main()
{
	func calFunc = add;
	cout << calFunc(4, 5) << endl;

	calFunc = [](int a, int b) {return a - b; };//含捕获列表时不可以赋值
	cout << calFunc(4, 5) << endl;

	system("pause");
	return 0;
}

输出:

9
-1
请按任意键继续. . .

2.7模板类型别名

template <typename Val>
struct strMap
{
	typedef map<string, Val> type;
};

strMap<int>::type m_map;

3.using

3.1概述

c++11中通过 using来定义别名,比typedef更容易阅读

3.2定义类型别名

using intPtr = int *;
 intPtr x = new int(6);

3.3定义函数指针别名

#include "iostream"
using namespace std;

using func = int(*)(int a, int b);

int add(int a, int b)
{
	return a + b;
}
int sub(int a, int b)
{
	return a - b;
}

int main()
{
	func calFunc = add;
	cout << calFunc(4, 5) << endl;

	system("pause");
	return 0;
}

3.4定义函数指针别名

#include "iostream"
using namespace std;

using func = int(int a, int b);

int add(int a, int b)
{
	return a + b;
}

int sub(int a, int b)
{
	return a - b;
}

int main()
{
	func* calFunc = add;
	cout << calFunc(4, 5) << endl;

	system("pause");
	return 0;
}

3.5模板类型别名

template <typename Val>
using strMap = map<string, Val> type;
// 使用using 更方便
strMap<int> m_map;

参考:C++中定义别名的几种方式总结