C++第四次作业

懵懂的女人 提交于 2019-12-01 07:11:47

类的继承与派生

定义与语法

类的继承是指**新的类从已有类那里得到已有的特性;从已有类产生新类的过程就是累的派生**。原有的类成为**基类**或**父类**,产生的新类称为**派生类**或**子类**。
语法:
class <派生类名>:<继承方式>  <基类①>, <继承方式>  <基类②>,.... ,  <继承方式>  <基类N>
{
    <派生类成员声明>;
};
  • 例: 假设基类Base1和Base2是已经定义的类,下面定义一个Derived的派生类:
class Derived: public Base1, private Base2
{
public:
    Derived();
    ~Derived();
};

访问控制

  • 公有继承:
    • 当类的继承方式为公有继承是,基类的公有成员和保护成员的访问属性在派生类中不变,而基类的私有成员不可直接访问。
  • 当类的继承方式为室友继承时,基类的公有成员和保护成员都以私有成员身份出现在派生类中,而基类的私有成员不可直接访问。
  • 例:
#include<iostream>

using namespace std;

class Point {
private:
    float x, y;

public:
    void initP(float xx, float yy)
    {
        x = xx;
        y = yy;
    }

    void Move(float xOff, float yOff)
    {
        x = xOff;
        y = yOff;
    }

    float GetX() { return x; }
    float GetY() { return y; }
};

class Rectangle : public Point {
private:
    float W, H;

public:
    void initR(float x, float y, float w, float h)
    {
        initP(x, y);
        W = w;
        H = h;
    }

    float GetW() { return W; }
    float GetH() { return H; }
};

int main()
{
    Rectangle Trigger;
    Trigger.initR(1, 2, 3, 4);
    Trigger.Move(5, 6);
    cout << "H : " << Trigger.GetX() << endl;
    cout << "W : " << Trigger.GetY() << endl;
    cout << "X : " << Trigger.GetW() << endl;
    cout << "Y : " << Trigger.GetH() << endl;
        return 0;
}
  • 结果:
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!