用法一:命名空间
这种用法估计使用最多的,为了防止定义变量名、函数名冲突,把它们定义在一个命名空间内,使用的时候需要进行命名空间的申明: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);
}