#include<iostream>
using namespace std;
class father
{
private:
int a;
protected:
int b;
public:
int c;
};
class son:public father
{
private:
int a;
};
int main()
{
cout<<sizeof(son)<<endl;
return 0;
}
[root@Orz 10:36 ~]# run
16
结论:继承父类全部特性
公有继承:
子类继承方式 |
父类属性整合进子类 | ||
public |
protected |
private | |
public继承 |
public |
protected |
禁止直接访问 |
protected继承 |
protected |
protected |
禁止直接访问 |
private继承 |
private |
private |
禁止直接访问 |
从对象角度:
一个对象只能访问一个类的共有属性,类的保护属性和私有属性是只有通过共有属性和友元函数间接访问
从类角度讲:
父类的保护属性,在子类中可以直接访问
父类的隐有属性,子类无法直接访问,这是一类区别另一个类的核心属性
1.公开继承public
#include<iostream>
using namespace std;
class Father
{
private:
int a;
protected:
int b;
public:
int c;
Father(int a = 1, int b = 2, int c = 3) :a(a), b(b), c(c) {}
void print()
{
cout << "Father" << a << endl;
cout << "Father" << b << endl;
cout << "Father" << c << endl;
}
};
class Son :public Father//公开继承
{
private:
int d;
public:
Son(int a = 1, int b = 2, int c = 3, int d = 4) :Father(a, b, c), d(d) {}
void show()
{
//cout <<"Son from Father" << a << endl;//父类private无法直接访问
cout << "Son from Father" << b << endl;//父类protected整合进子类protected
cout << "Son from Father" << c << endl;//父类public整合进子类public
cout << "Son" << d << endl;
}
};
int main()
{
Son son;
son.c = 3;//继承Father public对外公开
son.print();///继承Father protect对外公开
son.show();
return 0;
}
2.保护继承protected
#include<iostream>
using namespace std;
class Father
{
private:
int a;
protected:
int b;
public:
int c;
Father(int a = 1, int b = 2, int c = 3) :a(a), b(b), c(c) {}
void print()
{
cout << "Father" << a << endl;
cout << "Father" << b << endl;
cout << "Father" << c << endl;
}
};
class Son :protected Father//保护继承
{
private:
int d;
public:
Son(int a = 1, int b = 2, int c = 3, int d = 4) :Father(a, b, c), d(d) {}
void show()
{
//cout <<"Son from Father" << a << endl;//父类private无法直接访问
cout << "Son from Father" << b << endl;//父类protected仍然为子类protected
cout << "Son from Father" << c << endl;//父类public沦为子类protected
cout << "Son" << d << endl;
}
};
int main()
{
Son son;
//son.c = 3;//父类public沦为子类protected,外界无法访问
//son.print();//父类public沦为子类protected,外界无法访问
son.show();
return 0;
}
3.私有继承private
#include<iostream>
using namespace std;
class Father
{
private:
int a;
protected:
int b;
public:
int c;
Father(int a = 1, int b = 2, int c = 3) :a(a), b(b), c(c) {}
void print()
{
cout << "Father" << a << endl;
cout << "Father" << b << endl;
cout << "Father" << c << endl;
}
};
class Son :private Father//私有继承
{
private:
int d;
public:
Son(int a = 1, int b = 2, int c = 3, int d = 4) :Father(a, b, c), d(d) {}
void show()
{
//cout <<"Son from Father" << a << endl;//父类private无访问
cout << "Son from Father" << b << endl;//父类protected沦为子类private
cout << "Son from Father" << c << endl;//父类public沦为子类private
cout << "Son" << d << endl;
}
};
int main()
{
Son son;
//son.c = 3;//父类public沦为子类protected,外界无法访问
//son.print();//父类public沦为子类protected,外界无法访问
son.show();
return 0;
}