#include<iostream>
using namespace std;
class A{
protected:
int i;
public:
A(){
i = 10;
}
void test(){
cout << "abc" << endl;
}
};
class B:private A{
public:
B(){
test();
cout << i << endl;
}
};
int main(){
B b;
//b.test(); //inaccessible
//cout << b.i << endl;//inaccessible
}
abc
10
私有继承和受保护继承的派生类都可以和公有继承一样访问和修改基类的proteced和public的变量。
但
公有继承派生类的对象:可以直接访问和修改基类的公有变量,但不可以访问和修改受保护的
受保护继承和私有继承的派生类的对象:不可以直接访问和修改基类的任何变量
#include<iostream>
using namespace std;
class A{
public:
int i;
A():i(0),j(0){};
protected:
int j;
};
class B:public A{
public:
B(){cout << j << endl;}
};
class C:protected A{
public:
C(){cout << i << "," << j << endl;}
};
class D:private A{
public:
D(){
i = 1,j=2;
cout << i << "," << j << endl;
}
};
int main()
{
A a;
B b;
C c;
D d;
b.i = 3;
//b.j = 4;//error
//c.i = 1;//error
//cout << d.i << endl;//error
}
0
0,0
1,2