using 關鍵字的三種用法
1. 指定命名空間,比如,在C++編碼學習之初常用的 using namespace std;
2. 在子類中引用父類中的變量,這種用法比較特殊,
class T5Base {
public:
T5Base() :value(55) {}
virtual ~T5Base() {}
void test1() { cout << "T5Base test1..." << endl; }
protected:
int value;
};
class T5Derived : private T5Base {
public:
//using T5Base::test1;
//using T5Base::value;
void test2() { cout << "value is " << value << endl; }
};
在上面例子中發現,
私有繼承了T5Base,這導致在T5Drived中 value變成了私有變量,只能在T5Derived中的函數使用,要想T5Derived對象直接訪問,就需要在public下面增加 using T5Base::value
T5Derived drive;
//在 增加using T5Base::value之前,下面調用會編譯失敗
drive.value
3. 指定別名
指定別名的方式很多,我們經常用的方式比如:
typedef int(*pFunc)(int a, int b); //pFunc爲函數指針
#define char* ptr; //ptr爲指向char的指針
那麼using 是怎麼實現的呢?
using A=char*
A Sprintf()
{
char* ptt=“abc”;
return ptt;
}
using pFUnc=int (*)(int); //函數指針
int z(int input);
pFunc t= z;
在上面的例子中 using A = type, type必須是一種類型。
與我們常用的方式相比,基本沒多大不相同,但是對於模板來說 using可以指定模板類型的類,typedef則不可以
#include <vector>
using namespace std;
class C
{
template<typename T>
using Vec=vector<T>;
Vec<int> d; //work
template<typename T>
typedef vector<T> Vec2; //wrong definition
}
至於原因可以查找c++11標準: we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters.