#include<iostream>
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 << "deried::y=" << bb.y << endl;
cout << "base::x=" << bb.gety() << endl;
cout << "deried::y=" << bb.gety() << endl;
return 0;
}
这次的上机任务是搞清“派生与继承中”的成员访问问题,其中我感觉难点就在于派生类对基类成员的访问规则会受继承方式的影响,应该是为了程序的安全性和独立性。总结来说就是基类成员在派生类中的访问属性遵循:①原public和原protected中遵循“从严”(继承方式和积累权限)②原为private的,都不能直接访问,属于上级私有。基类的访问大致应是类内和类外(main、其它类函数)。再有就是派生类对基类成员的访问又分为内部访问和对象访问,类似于基类的访问规则。所以我觉得在程序的编写中,应格外注意派生类的成员函数和派生类的对象对基类成员函数和数据成员的访问。