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.