zoukankan      html  css  js  c++  java
  • C++继承方式简介及公有继承

    继承方式简介及公有继承

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

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

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

      三种继承方式

      公有继承

      私有继承

      保护继承

      公有继承(public)

      继承的访问控制

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

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

      访问权限

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

        通过派生类的对象:只能访问public成员。

     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.h
     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.h
     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
  • 相关阅读:
    稀疏自编码器一览表
    ZOJ 3886 Nico Number(筛素数+Love(线)Live(段)树)
    K好数(DP)
    【BZOJ4025】二分图
    又一次认识java(七) ---- final keyword
    二分查找
    从朴素贝叶斯分类器到贝叶斯网络(下)
    最近感到深深的绝望,感觉自己太菜了
    leetcode No.19 删除链表的倒数第N个节点 (python3实现)
    leetcode No.94 二叉树的中序遍历 (python3实现)
  • 原文地址:https://www.cnblogs.com/xuelanga000/p/12820777.html
Copyright © 2011-2022 走看看