c++11中using的使用

用法一:命名空间

这种用法估计使用最多的,为了防止定义变量名、函数名冲突,把它们定义在一个命名空间内,使用的时候需要进行命名空间的申明:using namespace std;就不过多讲解。



用法二:alias的使用

using 还可以指定别名,比如using SO3d = SO3<double>; 那么它和typedef ,有什么区别?

  • 可读性
    我们使用typedef定义函数指针:typedef void (* FUN_) (int, int); 函数指针指向的函数返回值是void,输入参数是int, int型。
    我们使用using 定义函数指针:using FUN_ = void(*)(int, int);
    using的写法把别名的名字强制分离到了左边,而把别名指向的放在了右边,比较清晰

  • 指定模板的别名,而typedef不行
    假如我们定义一个类模板:
template<class _scale, int option>
class Person
{
public:
    _scale age;
    _scale name[option];
};

template<class _T>
using myperson = Person<_T, 6>;  // Ok

//typedef Person<_T, 6> myperson; // fail

myperson<int> p;


用法三:子类引用基类成员

  • 假如子类私有继承父类,子类无法使用父类的成员(变量,函数等),但是使用using可以访问,code如下:
template<class _scale, int option>
class Person
{
public:
    _scale age;
    _scale height;
    _scale name[option];

	void myprint(void)
	{
		cout << "age" << age << endl;
	}
};


template<class _scale, int option>
class HeighPerson : private Person<_scale, option>
{
public:
    using Person<_scale, option>::age; // 使用using 之后变成public
    using Person<_scale, option>::myprint; // 使用using, myprint之后变成public
    
protected:
	using Person<_scale, option>::height;  //在本来不可访问的,使用using 之后变成protected
    void test(void)
    {
	cout << "age" << age << endl;
    }
};

class Base
{
 public:
    void menfcn()
    {
        cout << "Base function" << endl;
    }

    void menfcn(int n)
    {
        cout <<  "Base function with int" << endl;
    }

};

class Derived : private Base
{
 public:
    using Base::menfcn;  //using声明只能指定一个名字,不能带形参表
    void menfcn(int a, int b)
    {
	cout << "derived function" << endl;
    }
};
int main()
{
    Base b;
    Derived d;
    b.menfcn();
    d.menfcn(2);  
    d.menfcn(2,3)

}

  • 申明继承父类构造函数
class Base
{

 public:
     Base(int a)
     {
	 cout << "base constructor"<< a << endl;
     }
};

class Derived : private Base
{
 public:
     using Base::Base;
};

int main()
{
    Base b(1);
    Derived d(2);

}


在这里插入图片描述

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值