C++11: using 的使用

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.
 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值