先给出代码:
#include<iostream>
using namespace std;
class A
{
public:
A(int x1)
{
x=x1;
}
void show()
{
cout<<"x="<<x<<endl;
}
private:
int x;
};
class B:private A
{
public:
B(int x1,int y1):A(x1)
{
y=y1;
}
A::show;
private:
int y;
};
int main()
{
B b(10,20);
b.show();
return 0;
访问声明机制可以个被调整私有派生类从基类继承下来的成员性质,从而使外界可以通过派生类的界面直接访问基类的某些成员,同时也不影响其他基类成员的访问属性。
访问声明在使用时应注意以下几点:
1 数据成员也可以使用访问声明。
例如:
class A
{
public:
int x2;
...
private:
...
};
class B:private A
{
public:
...
A::x2;
...
private:
...
};
2 访问声明中只含不带类型和参数的函数名或者变量名。如果把上面的访问声明写成:
void A::show;
或
A::show();
或
void A::show();
都是错误的。
3 访问声明不能改变成员在基类中的访问属性,也就是说,访问声明只能把原基类的保护成员调整为私有派生类的保护成员,把原基类的公有成员调整为私有派生类的公有成员。
但对基类的私有成员不能使用访问声明。 例如:
class A
{
public:
int x1;
protected:
int x2;
private:
int x3;
}
class B:private A
{
public:
A::x1; // T
A::x2; //F
A::x3; //F
protected:
A::x1; //F
A::x2; //T
A::x3; //F
private:
A::x3; //F
};
4 对于基类中的重载函数名,访问声明将对基类中所有同名函数起作用。这意味着对于重载函数使用访问声明时要慎重。