C++ using用法总结
1)配合命名空间,对命名空间权限进行管理
1using namespace std;//释放整个命名空间到当前作用域 2using std::cout; //释放某个变量到当前作用域
2)类型重命名
作用等同typedef,但是逻辑上更直观。
1#include <iostream>using namespace std;#define DString std::string //! 不建议使用!typedef std::string TString; //! 使用typedef的方式 2using Ustring = std::string; //!使用 using typeName_self = stdtypename;//更直观typedef void (tFunc*)(void);using uFunc = void(*)(void); 3int main(int argc, char *argv[]) 4{ 5 6 TString ts("String!"); 7 Ustring us("Ustring!"); 8 string s("sdfdfsd"); cout<<ts<<endl; 9 cout<<us<<endl; 10 cout<<s<<endl; 11 return 0; 12}
3)继承体系中,改变部分接口的继承权限。
有这样一种应用场景,比如我们需要私有继承一个基类,然后又想将基类中的某些public接口在子类对象实例化后对外开放直接使用。如下即可
1#include <iostream> 2//#include <array> 3#include <typeinfo> 4 5 6using namespace std; 7 8class Base 9{ 10public: 11 Base() 12 {} 13 ~Base(){} 14 15 void dis1() 16 { 17 cout<<"dis1"<<endl; 18 } 19 void dis2() 20 { 21 cout<<"dis2"<<endl; 22 } 23}; 24 25class BaseA:private Base 26{ 27public: 28 using Base::dis1;//需要在BaseA的public下释放才能对外使用, 29 void dis2show() 30 { 31 this->dis2(); 32 } 33}; 34 35int main(int argc, char *argv[]) 36{ 37 38 BaseA ba; 39 ba.dis1(); 40 ba.dis2show(); 41 42 return 0; 43}