起因:在看C++新特性的时候看到一段代码,在类里面使用了using,故学习总结一下C++using的使用。
1.命名空间的使用
当我们使用命名空间中声明的变量或者函数时,需要namespace::xxx
来使用
比如:std::cout << "hhh" << std::endl;
当我们使用cout时,需要指定他所在的命名空间cout
当然我们也可以在外部使用using namespace xxx
在其子域内,所以xxx命名空间中的内容都不需要在xxx::
来调用,当然这样不好
2. 在子类中引用基类的成员
先看一段代码
class A {
public:
void display() {
std::cout << "hhhh" << std::endl;
}
};
class B : private A {
};
子类B私有继承了A,display方法变为了私有的,我们对于A的对象,可以通过对象直接调用display(),但是如果在B里面则无法通过对象去调用display(),只能在B里面再封装一个public的方法,让他去调用A::display() ,
可以通过using
来达到使用B的对象来调用display()的目的。
class B : private A {
public:
using A::dis;
};
注意: 上述using只是引用,不需要指定形参
3. 别名指定
using custom_type int
这样我们使用custom_type type 时,相当于 int type;
*但是不是有个关键字typedef
就是用来指定别名的吗?
上栗子:
typedef std::vector<std::map<int, std::string>> VecMap;
using VecMap = std::vector<std::map<int, std::string>>
或许这个看起来他们两个都差不多,但是我们再看一个
typedef void (*callback) (int, const std::string&);
如果不熟悉函数指针和typedef,如果这里不叫callback而是其他,可能都不知道这是个函数指针的别名
但是如果使用using
using callback = void (*) (int, const std::string&);
哪个更清晰一目了然