#include
using namespace std;
class Base {
public:
void setx(int i)
{
x = i;
}
int getx()
{
return x;
}
public:
int x;
};
class Derived :public Base {
public:
void sety(int i)
{
y = i;
}
int gety()
{
return y;
}
void show()
{
cout << “Base::x=” << x << endl;
}
public:
int y;
};
int main()
{
Derived bb;
bb.setx(16);
bb.sety(25);
bb.show();
cout << “Base::x=” << bb.x << endl;
cout << “Derived::y=” << bb.y << endl;
cout << “Base::x=” << bb.getx() << endl;
cout << “Derived::y=” << bb.gety() << endl;
return 0;
}
1.将基类 Base 中数据成员 x 的访问权限改为 private 时,会出现哪些错误,为什么?
错误:Base::x无法访问
原因:x在Base声明中是private成员,派生类成员函数不能直接访问基类的私有成员。
2.将基类 Base 中数据成员×的访问权限改为 protected 时,会出现哪些错误,为什么?
错误:Base::x无法访问
原因:x在Base声明中是protected成员,是保护的,只允许内部和派生函数访问,类外不能调用。
3.在原程序的基础上,将派生类Derived 的继承方式改为 private 时,会出现哪些错误,为什么?
错误:Base::x不可访问;Base::getx不可访问;Base::setx不可访问。
原因:Derived使用private从Base无法继承。
4.在原程序的基础上,将派生类Derived 的继承方式改为 protected 时,会出现哪些错误,为什么?
错误:Base::x不可访问;Base::getx不可访问;Base::setx不可访问。
原因:Derived使用protected从Base继承,类外无法调用。