Last updated:2026-10-12
C++ using Declarations and Aliases¶
About the Author:¶
Personal WeChat official account:

Basic Usage¶
Local and global using; see the cases below for the concrete operations and usage:
#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;
}
Changing Accessibility¶
class Base{
public:
std::size_t size() const { return n; }
protected:
std::size_t n;
};
class Derived : private Base {
public:
using Base::size;
protected:
using Base::n;
};
Class Derived privately inherits Base, so for it the member variable n and the member function size are private. By using using declarations, their accessibility can be changed: in the example above, size can be accessed with public permission and n with protected permission. For the complete code see: derived_base.cpp
Function Overloading¶
During inheritance, a derived class can override zero or more instances of an overloaded function; as soon as one overloaded version is defined, all the other overloaded versions become invisible.
If, for a set of overloaded functions in a base class, we need to change one of them in the derived class and keep the others visible, we would have to redefine every version, which is extremely tedious.
#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;
}
For the complete code see: using_derived.cpp
Replacing typedef¶
In C, the syntax typedef A B is common: it defines B as type A, that is, it gives type A the alias B.
Corresponding to typedef A B, using B=A performs the same operation.
For the complete code see: using_typedef.cppRelated Topics¶
- C++ Pure Virtual Functions and Abstract Classes | C++那些事
- C++ assert | C++那些事
- C++ Bit Fields | C++那些事
- Implementing C++ Polymorphism in C | C++那些事
- C++ const Constants and Qualifiers | C++那些事
- The Complete C++ const Family | C++那些事
- C++ Dereference Operator * | C++那些事
- C++ Initialization and Assignment | C++那些事
- Ways to Return Multiple Values in C++ | C++那些事
- C++ mutable Keyword | C++那些事