zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【C++】第三篇(基础)继承与多继承

C++基础继承 第三篇
2023-09-14 09:14:31 时间

C++继承

在面向对象程序设计中最重要的一个概念是继承,继承允许我们依据一个类来定义一个类,这使得创建和维护一个应用程序变得很容易,这样做也达到了重用代码功能和提高执行效率的效果。
当创建一个类的时候,你不需要重新写入新的数据成员和成员函数,只需要指定新建的类继承了一个已有的类的成员即可,这个已有的类称为基类,新建的类称为派生类。
例如:

using namespace std;

class Animal{
    //吃饭
    //睡觉
};

class Dog:public Animal{
    //叫声
};

另外,一个类可以派生多个类,它可以从多个基类继承函数和数据。
形式如下:

class Dog:public Animal

下面看具体实例:

#include<iostream>
using namespace std;

class Shape{
public:
    void setWidth(int a){
        width=a;
    }
    void setHeight(int b){
        height=b;
    }

protected:
    int width;
    int height;
};

class Rectangle:public Shape{
public:
    int getArea(){
        return (width*height);
    }
};

int main(){
    Rectangle shape1;
    int Area;
    shape1.setWidth(10);
    shape1.setHeight(10);
    Area=shape1.getArea();
    cout<<"面积为:"<<Area<<endl;

    return 0;
}

派生类可以访问基类中所有的非私有成员。因此基类成员如果不想被派生类的成员函数访问,则应在基类中声明为 private。
一个派生类继承了所有的基类方法,但下列情况除外:
基类的构造函数、析构函数和拷贝构造函数。
基类的重载运算符。
基类的友元函数。

C++多继承

多继承即一个子类可以有多个父类,它继承了多个父类特性。
例如:

class 新类名:public 类名,public 类名

具体实例:

#include<iostream>
using namespace std;

class Shape{
public:
    void setWidth(int a){
        width=a;
    }
    void setHeight(int b){
        height=b;
    }

protected:
    int width;
    int height;
};

class PaintCost{
public:
    int getCost(int area){
        return 50*area;
    }
};

class Rectangle:public Shape,public PaintCost{
public:
    int getArea(){
        return (width*height);
    }
};

int main(){
    Rectangle Rect;
    int Area;
    Rect.setWidth(10);
    Rect.setHeight(10);
    Area=Rect.getArea();
    cout<<"面积为:"<<Area<<endl;
    cout<<"花费为:"<<Rect.getCost(Area)<<endl;

    return 0;
}