C++继承方式简介及公有继承

继承方式简介及公有继承

不同继承方式的影响主要体现在:

1.派生类成员对基类成员的访问权限

2.通过派生类对象对基类成员的访问权限

三种继承方式

公有继承

私有继承

保护继承

公有继承(public)

继承的访问控制

基类的public和protected成员:访问属性在派生类中保持不变;

基类的private成员:不可访问。

访问权限

派生类的成员函数;可以直接访问基类的public和protected成员,private成员;

通过派生类的对象:只能访问public成员。
C++继承方式简介及公有继承C++继承方式简介及公有继承

1 #ifndef _POINT_H
 2 #define _POINT_H
 3 
 4 class Point {
 5     //基类point类的定义
 6 public:
 7     //公有成员函数
 8     void initPoint(float x = 0, float y = 0) {
 9         this->x = x;
10         this->y = y;
11     }
12     void move(float offx, float offy) {
13         x += offx;
14         y += offy;
15     }
16     float getX() const { return x; }
17     float getY() const { return y; }
18 
19 private:
20     //私有数据成员
21     float x, y;
22 
23 };
24 
25 #endif // !_POINT_H

Point.hC++继承方式简介及公有继承C++继承方式简介及公有继承

1 #ifndef _RECTANGLE_H
 2 #define _RECTANGLE_H
 3 #include "point.h"
 4 class Rectangle :public Point {
 5     //派生类定义部分
 6 public:
 7     //新增公有函数成员
 8     void initRectangle(float x, float y, float w, float h) {
 9         initPoint(x, y); //调用基类公有成员函数
10         this->w = w;
11         this->h = h;
12     }
13     float getH() const { return h; }
14     float getW() const { return w; }
15 private:
16     //新增私有数据成员
17     float w, h;
18 };
19 #endif // !_RECTANGLE_H

Rectangle.hC++继承方式简介及公有继承C++继承方式简介及公有继承

1 #include <iostream>
 2 #include <cmath>
 3 #include "rectangle.h"
 4 using namespace std;
 5 
 6 
 7 int main()
 8 {
 9     Rectangle rect; //定义rectangle类对象
10     //设置矩形的参数
11     rect.initRectangle(2, 3, 20, 10);
12     rect.move(3, 2); //移动矩形数据
13     cout << "the data of rect(x,y,w,h):" << endl;
14     //输出矩形的特征参数
15     cout << rect.getX() << ","
16         << rect.getY() << ","
17         << rect.getW() << ","
18         << rect.getH() << endl;
19     return 0;
20 }

main.c

原文链接: https://www.cnblogs.com/xuelanga000/p/12820777.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/196867

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午7:23
下一篇 2023年2月12日 下午7:23

相关推荐