1、可以通过命名空间显示的把基类中的成员引入到派生类中。
先看一个例子:
class X
{
public :
void f(char);
};
class Y : public X
{
public :
void f(int); //hides base class's f
};
void f()
{
X x;
x.f('a'); //calls D::f
}
如果想在这个时候调用基类中的版本,就可以通过using来达到目的:
class X
{
public :
void f(char);
};
class Y : public X
{
public :
void f(int)
using B::f;
};
void f()
{
X x;
x.f('a'); //calls B::f
}
命名空间还可以用来消除多重继承造成的歧义性。
class X
{
public :
void f(char);
};
class Y :
{
public :
void f(int);
};
class Z : public X, public Y
{
public :
void g()
{
f('a'); // error: X::f or Y::f
f(1); //error : X::f or Y::f
}
};
在这种情况下,就可以用命名空间来消除这个歧义性。修改类Z, 其他代码不变:
class Z : public X, public Y
{
using X::f;
using Y::f;
public :
void g()
{
f('a'); // ok: X::f
f(1); //ok : Y::f
}
};
C++为了避免混乱,作为成员的使用声明必须使用名字(直接或间接的)提出基类的一个成员。为了避免和支配规则发生冲突,不允许将使用指示作为类的成员。也就是说,下面两种形式都是错误的:
void f();
class X
{
public :
using namespace A; //error : using-directive as mumber
using ::f; //error : need a name
};
可以通过命名空间改变继承自基类的一些成员的访问权限,但是仅限于因为派生方式而改变的访问权限:
#include <iostream>
class X
{
public :
int x;
private :
int a;
public :
void f() { std::cout << "this is X" << std::endl; }
};
class Y : private X
{
public :
using X::a; //error : a cannot be interview
using X::f;
};
void g(Y &y)
{
y.x++; // error : x cannot be interview
y.f(); // ok
}
int main()
{
Y y;
g(y);
system("PAUSE");
return 0;
}