前言
C++ using 常见用法
Code
常规使用
#include <iostream>
// #define isNs1 1
#define isGlobal 2
using namespace std;
void func()
{
cout<<"::func"<<endl;
}
namespace ns1 {
void func()
{
cout<<"ns1::func"<<endl;
}
}
namespace ns2 {
#ifdef isNs1
using ns1::func; /// ns1中的函数
#elif isGlobal
using ::func; /// 全局中的函数
#else
void func()
{
cout<<"other::func"<<endl;
}
#endif
}
int main()
{
/**
* 这就是为什么在c++中使用了cmath而不是math.h头文件
*/
ns2::func(); // 会根据当前环境定义宏的不同来调用不同命名空间下的func()函数
return 0;
}
result
::func
改变访问权限
通过在类的内部使用using声明语句 , 我们可以将该类的直接或间接基类中的任何可访问成员标记出来 (只限于非私有成员) 。
using声明语句中名字的访问权限由该using声明语句之前的访问说明符来决定。
#include <iostream>
using namespace std;
class Base1 {
public:
Base1():value(10) {}
virtual ~Base1() {}
void test1() { cout << "Base test1..." << endl; }
protected: // 保护
int value;
};
// 默认为私有继承
class Derived1 : Base1 {
public:
void test2() { cout << "value is " << value << endl; }
};
/**
* 子类对父类成员的访问权限跟如何继承没有任何关系,
* “子类可以访问父类的public和protected成员,不可以访问父类的private成员”——这句话对任何一种继承都是成立的。
*
*/
class Base {
public:
Base():value(20) {}
virtual ~Base() {}
void test1() { cout << "Base test1..." << endl; }
// private: //私有
int value;
};
class Derived : Base {
public:
using Base::value;
void test2() { cout << "value is " << value << endl; }
};
int main()
{
Derived1 d1;
d1.test2();
Derived d;
d.test2();
return 0;
}
result
value is 10
value is 20
函数重载
#include <iostream>
using namespace std;
class Base{
public:
void f(){ cout<<"f()"<<endl;
}
void f(int n){
cout<<"Base::f(int)"<<endl;
}
};
class Derived : private Base {
public:
using Base::f;
void f(int n){
cout<<"Derived::f(int)"<<endl;
}
};
int main()
{
Base b;
Derived d;
d.f();
d.f(1);
return 0;
}
result
f()
Derived::f(int)