●注意:private权限的属性,任何继承方式都不能在子类中访问.
(1)public: 父类中public属性,protected属性,被继承后在子类中权限和父类中的以前一样.
class A
public:
int dataAl ;
protected:
int dataA2;
};
class B:pub1ic A
{
//继承后的dataA1在子类里也是public权限.
//继承后的dataA2在子类里也是protected权限.
};
——————————————————————————
(2)protected: 父类中属性的权限,被继承后在子类中的变成protected权限
(3)private: 父类中public属性, protected属性, 被继承后在子类中的全部变成private权限
●注意: private权限的属性, 有被子类继承,但是访问被编译器屏蔽,因此访问不了
代码:
#include <iostream>
using namespace std;
class A
{
public:
A():dataA1(0),dataA2(1),dataA3(2)
{
cout<<"A constructor"<<endl;
}
int dataA1;
protected:
int dataA2;
private:
int dataA3;
};
class B:public A
{
public:
void Visit()
{
cout<<this->dataA1<<endl;
cout<<this->dataA2<<endl;
//cout << this->dataA3 << endl; //error
}
int _dataB;
};
class C:protected A
{
public:
void Visit()
{
cout<<this->dataA1<<endl;
cout<<this->dataA2<<endl;
//cout<<this->dataA3<<endl; //error
}
};
void test01()
{
B b1;
cout<<b1.dataA1<<endl;
b1.Visit();
//cout<<b1.dataA2<<endl;
//cout<<b1.dataA3<,endl;
}
void test02()
{
C c1;
c1.Visit();
//cout<<c1.dataA1<<endl; //protected error!
}
void test03()
{
cout<<"sizeof(A):"<<sizeof(A)<<endl;
cout<<"sizeof(B):"<<sizeof(B)<<endl;
}
int main(int argc, char *argv[])
{
test03();
return 0;
}