#include<iostream>
using namespace std;
class Base {
public:
void setx(int i)
{
x = i;
}
int getx() {
return x;
}
private:
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;
}
x为基类中的私有数据,派生类中的函数无法调用。
x为基类中的保护数据,派生类中的函数无法调用。
私有继承时:派生类无法调用基类中的成员函数和数据。
保护继承时:基类中的函数和成员对派生类都是保护的,不可直接访问。
心得:
公有成员:类内类外都可访问
私有成员:类内可以访问,类外不可以访问,友元可以访问
保护成员:不涉及成员与私有相同