继承的概念
面向对象中的继承指类之间的父子关系
-
子类拥有父类的所有成员变量和成员函数
-
子类就是一种特殊的父类
-
子类对象可以当作父类对象使用
-
子类可以拥有父类没有的方法和属性
继承初体验
深入了解继承
C++中的访问级别与继承
继承时的访问级别设定会影响到成员的访问级别
注意:
-
C++中class的继承默认为private继承
-
private继承的子类拥有父类的所有成员
-
private继承使得父类的所有成员在子类中变为private成员
-
public继承
-
父类成员在子类中保持原有访问级别
-
-
private继承
-
父类成员在子类中变为private成员
-
#include <cstdlib>
#include <iostream>
using namespace std;
class Parent
{
private:
int a;
public:
Parent()
{
a = 1000;
}
void print()
{
cout<<"a = "<<a<<endl;
}
};
class Child : public Parent//默认继承private public继承保持原状
{
};
int main(int argc, char *argv[])
{
Parent parent;
Child child;
parent.print();
//child.print();//ops private为私有继承。没有继承过来?
child.print();//public继承后可以了
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
result:
a = 1000
a = 1000
Press the enter key to continue ...
为子类添加新的成员
class Parent
{
private:
int a;
public:
Parent()
{
a = 1000;
}
void print()
{
cout<<"a = "<<a<<endl;
}
};
class Child : public Parent
{
private:
int b;
public:
void set(int a, int b)
{
//this->a = a;//ops!!!私有成员只能在本类中被访问
//a在Parent类中,在Child类中明显是在外部
this->b = b;
}
};
类成员的访问级别只有public和private是否足够?
一刀切是不足以描述世界的
新的关键字----类的protected成员
类的protected成员
-
protected成员可以在子类中被访问,但不能在外界被访问
-
protected成员的访问权限介于public和private之间
#include <cstdlib>
#include <iostream>
using namespace std;
class Parent
{
protected:
int a;
public:
Parent()
{
a = 1000;
}
void print()
{
cout<<"a = "<<a<<endl;
}
};
class Child : public Parent
{
protected:
int b;
public:
void set(int a, int b)
{
//Parent中protected成员可以在子类中被访问
this->a = a;
this->b = b;
}
};
int main(int argc, char *argv[])
{
Parent parent;
Child child;
//Child.a = 0;//ops!!!protected成员不能在外界被访问
parent.print();
child.print();
child.set(100,200);//parent.print();并没有改变,改变的是chil
parent.print();
child.print();
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
result:
a = 1000
a = 1000
a = 1000
a = 100
Press the enter key to continue ...
如何恰当的使用public,protected和private为成员声明访问级别??
继承与访问级别
类成员访问级别设置的原则
-
需要被外界访问的成员直接设置为public
-
只能在当前类中访问的成员设置为private(不能被外界访问的一般定成这个⭐)
-
只能在当前类和子类中访问的成员设置为protected
private成员在子类中依然存在,但是却无法访问到。