1 什么是继承
继承概念
继承(inheritance)机制是面向对象程序设计使代码可以复用的最重要的手段,它允许程序员在保持原有类特性的基础上进行扩展,增加功能。这样产生新的类,称派生类。继承呈现了面向对象程序设计的层次结构,体现了由简单到复杂的认知过程。
面向对象的继承关系指类之间的父子关系。用类图表示如下:

2 为什么要有继承?/ 继承的意义?
因为继承是面向对象中代码复用的一种手段。通过继承,可以获取父类的所有功能,也可以在子类中重写父类已有的功能 以及 添加父类中没有的功能。
3如何理解 子类是特殊的父类?
因为子类不仅继承了父类所有的属性与行为,而且在子类中还可以重写父类已有的功能,以及添加自己的新属性与新方法。这也就是说子类对象可以当作父类对象使用。
4 继承的规则
1) 子类是特殊的父类
2) 子类对象可以直接初始化父类对象
3) 子类对象可以直接赋值给父类对象
5 继承中的访问级别
1)public:在类的内部和外部都可以访问。
2)protected::可以在类的内部使用,不可以在类的外部直接使用。,但是存在继承关系时,可以在子类中使用父类的protected的成员。
3)private:只可以在类的内部使用,不可以在类的外部使用。
注:类的内部:在当前类的作用域中(不包括子类的作用域);类的外部:类内部之外的作用域(包括子类的作用域)
问题1:子类是否可以直接访问父类中的private成员(非公有成员)吗?(No)
1)从面向对象理论的角度分析,可知子类拥有父类一切的属性与行为,得出的结论:Yes
2)从c++的语法角度分析,可知外界不能访问类的private成员,得出的结论:No
问题2:谈谈 protected关键字的存在的意义?
protected关键字是为继承而存在的,这样就可以在子类中访问父类的protected成员,同时还不允许外界直接访问父类中的protected成员。
问题3:在类中如何选择类的访问级别?--- 见下图

6 继承中的继承方式
1)public 继承方式 --- 父类成员在子类中保持原有的访问级别。
2)protected继承方式 ---父类中的公有成员在子类中变成了protected成员,其它不变。
3)private 继承方式(默认) --- 父类成员在子类中变成了private成员
可归纳为:

结论:无论选择哪种继承方式,都不会影响子类访问父类成员的级别
注:1) c++ 工程项目中只使用 public 继承方式;
2) c++ 派生语言(jave,c#)只支持 public继承方式;
3)protected、private 继承方式带来的复杂性远大于其实用性;(舍弃不用)
用代码实现类图中的功能:

代码如下:
- #include <iostream>
- #include <string>
- #include <sstream>
-
- using namespace std;
-
- class Object
- {
- protected:
- string mName;
- string mInfo;
- public:
- Object()
- {
- mName = "Object";
- mInfo = "";
- }
- inline string getName()
- {
- return mName;
- }
- inline string getInfo()
- {
- return mInfo;
- }
- };
-
- class Point : public Object
- {
- private:
- int mX;
- int mY;
- public:
- Point(int x = 0, int y = 0)
- {
- ostringstream oss;
-
- mX = x;
- mY = y;
- mName = "Point";
-
- oss << "Point(" << mX << ", " << mY << ")";
- mInfo = oss.str();
- }
- inline int getX()
- {
- return mX;
- }
- inline int getY()
- {
- return mY;
- }
- };
-
- class Line : public Object
- {
- private:
- Point mP1;
- Point mP2;
- public:
- Line(Point p1, Point p2)
- {
- mP1 = p1;
- mP2 = p2;
- mName = "Line";
- mInfo = "Line from " + p1.getInfo() + " to " + p2.getInfo();
- }
- inline Point getStartPoint()
- {
- return mP1;
- }
- inline Point getEndPoint()
- {
- return mP2;
- }
- };
-
- int main(int argc, char const *argv[])
- {
- Object obj;
- cout << obj.getName() << endl;
- cout << obj.getInfo() << endl << endl;
-
- Point p1(1, 2);
- Point p2(3, 4);
- cout << p1.getName() << endl;
- cout << p1.getInfo() << endl;
- cout << p2.getName() << endl;
- cout << p2.getInfo() << endl << endl;
-
- Line line(p1, p2);
- cout << line.getName() << endl;
- cout << line.getInfo() << endl << endl;
-
- return 0;
- }
到此这篇关于c++中的继承关系的文章就介绍到这了,更多相关c++继承关系内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!