c++继承知识点小结

继承的概念

继承是c++中一个重要的概念。继承是指,我们可以使用一个类来定义另一个类,在创建这个类时,我们就不需要重新编写数据成员与成员函数,这可以大大方便我们编写代码和维护代码的效率。

当我们使用一个类来定义另一个类时,前者就称为基类,后者就称为派生类

类派生的方式

为了派生一个类,我们可以指定一个类继承列表,列表可以有一个类,或者多个类,类继承的形式如下:

class Rectangle: public Shape	//其中Rerangle 是派生类,shape是继承类

其中 : public位置的修饰符可以为:public,protected,private,他们的意思分别是

  • public :当从一个公有基类派生一个类的时候,基类的公有成员成为派生类的公有成员;基类的保护成员成为派生类的保护成员。一个基类的私有成员不能被派生类直接访问,但可以通过调用基类的公有和保护成员访问基类的私有成员。
  • protected :当从一个受保护的基类派生子类的时候,基类的公有和保护成员成为派生类的保护成员。
  • private :当从一个私有的基类派生子类的时候,基类的公有和保护成员成为派生类的私有成员。

这个位置也可以空缺,它的默认情况是private

比如:

#include <iostream>
using namespace std;

class Shape 
{
public:
    Shape(){width = 0,height = 1;};
    void init(double w,double h){
        width = w;
        height = h;
    }
    double get_w(){return width;}
    double get_h(){return height;}
    friend class Retangle;
private:
    double width;
    double height;
};

class Rectangle: public Shape
{
public:
    Rectangle(double xx,double yy,double w,double h){
        init(w,h);
        x = xx;
        y = yy;
    }
    void move(int px,int py){x-=px,y-=py;}
    double get_x(){return x;}
    double get_y(){return y;}
private:
    double x,y;
};

int main(void)
{
    Rectangle rect(1,2,3,4);
    cout<<rect.get_x()<<" "<<rect.get_y()<<" "<<rect.get_w()<<" "<<rect.get_h()<<endl;
    int xx,yy;
    cin>>xx>>yy;
    rect.move(xx,yy);
    cout<<rect.get_x()<<" "<<rect.get_y()<<" "<<rect.get_w()<<" "<<rect.get_h()<<endl;


    return 0;
}

程序运行结果

1 2 3 4
1 2	//input
0 0 3 4

这里的Shape就是基类,Retangle就是派生类。

需要注意的是:无论哪种继承,静态成员,静态成员函数与友元函数都无法被继承

类的多继承

上述继承为类的单继承的应用,多继承可以派生一个到多个基类。

比如:

#include<iostream>

using namespace std;

class A {
public:
    A(int x) : x(x){}
    int get_x() {return x;}
private:
    int x;
};  

class B {
public:
    B(int y) : y(y){}
    int get_y() {return y;}
private:
    int y;
};

class C : public A, public B {
public:
    C(int x,int y) : A(x), B(y) {}
    void print() {
        cout<<get_x()<<endl;
        cout<<get_y()<<endl;
    }
};

int main() {
    C c(1,2);
    c.print();
    return 0;
}

输出为

1
2
posted @ 2019-10-13 10:48  _Rainy  阅读(465)  评论(0编辑  收藏  举报