C++——继承

C++——继承

继承基本概念

继承是面向对象编程(OOP)中的一个核心概念,特别是在C++中。它允许一个类(称为派生类或子类)继承另一个类(称为基类或父类)的属性和方法。继承的主要目的是实现代码重用,以及建立一种类型之间的层次关系。

特点

  1. 代码重用:子类继承了父类的属性和方法,减少了代码的重复编写。

  2. 扩展性:子类可以扩展父类的功能,添加新的属性和方法,或者重写(覆盖)现有的方法。

  3. 多态性:通过继承和虚函数,C++支持多态,允许在运行时决定调用哪个函数。

基本用法

在C++中,继承可以是公有(public)、保护(protected)或私有(private)的,这决定了基类成员在派生类中的访问权限。

#include <iostream>
using namespace std;
//基类,父类
class Vehicle{ //交通工具,车,抽象的概念
    public:
    string type;
    string contry;
    string color;
    double price;
    int numOfWheel;
    void run(){
        cout << "车跑起来了" << endl;
    }
    void stop();
};
//派生类,子类
class Bickle : public Vehicle{
};
//派生类,子类
class Roadster : public Vehicle{ //跑车,也是抽象,比父类感觉上范围缩小了点
    public:
    int stateOfTop;
    void openTopped();
    void pdrifting();
};
int main()
{
    Roadster ftype;
    ftype.type = "捷豹Ftype";
    ftype.run();
    Bickle bike;
    bike.type = "死飞";
    bike.run();
    return 0;
}

在这个例子中, Vehicle 类公有地继承自 Vehicle 类,这意味着所有 Vehicle 类的公有成员在

Vehicle 类中也是公有的。

分文件实现继承

让我们用一个简单而有趣的案例来说明继承的概念:动物园中的动物。

想象我们正在创o在这个程序中,我们有一个基类 Animal ,它定义了所有动物共有的特性和行为。然后,我们可以创建几个派生类,如 Lion 、 Elephant 和 Bird ,这些类继承自 Animal 类,并添加或修改特定于它们自己的特性和行为。

Animal.h

#ifndef ANIMAL_H
#define ANIMAL_H
#include<iostream>
#include<string>

using namespace std;

class Animal
{
public:
    string name;
    int age;

    Animal();
    void makeSound();
    void eatFood();
};

#endif // ANIMAL_H

lion.h

#ifndef LION_H
#define LION_H
#include "animal.h"

class Lion : public Animal
{
public:
    int sleepTime;

    Lion();
    void hunting();
};

#endif // LION_H

cat.h

#ifndef CAT_H
#define CAT_H
#include "animal.h"

class cat : public Animal
{
public:
    cat();

    void eatFish();
    void digAhole();
};

#endif // CAT_H

animal.cpp

#include "animal.h"

Animal::Animal()
{

}

void Animal::makeSound()
{
    cout<<"动物叫"<<endl;
}

void Animal::eatFood()
{
    cout<<"动物吃饭"<<endl;
}

lion.cpp

#include "lion.h"

Lion::Lion()
{

}

void Lion::hunting()
{
      cout<<"狮子打猎"<<endl;
}

cat.cpp

#include "cat.h"

cat::cat()
{

}

void cat::eatFish()
{
    cout<<"猫吃鱼"<<endl;
}

void cat::digAhole()
{
    cout<<"猫挖洞拉屎"<<endl;
}

main.cpp

#include <iostream>
#include "animal.h"
#include "lion.h"
#include "cat.h"

using namespace std;

int main()
{
    Animal a;
    a.makeSound();

    Lion l;
    l.makeSound();
    l.hunting();

    cat cat;
    cat.eatFish();
    return 0;
}
  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值