【CPP】using 用法整理

[toc]

简单整理一下using的用法

一、命名空间

命名空间的用法相对简单哈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using namespace std;

using std::cout;

//////////////////////////

namepsapce nsmine {
void cout();
namespace minedefine {
#define MINE "mine"
}
}

using namespace nsmine;
using nsmine::minedefine;

二、使用using起别名

相当于 typedef

1
2
typedef 	std::vector<int> intvec;
using intvec = std::vector<int>;

以上两种写法等价。同样两种方式也都适用于函数别名的声明。如下所示:

1
2
// 代码 2-2
typedef void (*FP) (int, const std::string&);

代码 2-2 使用 typedefvoid (int, const std::string&) 创建了一个别名 FP。同样我们使用using来做这个操作,函数返回类型是void,接收参数为int,const std::string&

1
using Fp = void (*) (int, const std::string&);

using的写法把别名的名字强制分离到了左边,而把别名指向的放在了右边,比较清晰,可读性比较好。比如:

1
2
3
typedef std::string (Foo::* fooMemFnPtr) (const std::string&);

using fooMemFnPtr = std::string (Foo::*) (const std::string&);

【CPP】using 用法整理
https://hodlyounger.github.io/B_Code/CPP/【CPP】using/
作者
mingming
发布于
2023年10月27日
许可协议