C++——继承
继承基本概念
继承是面向对象编程(OOP)中的一个核心概念,特别是在C++中。它允许一个类(称为派生类或子类)继承另一个类(称为基类或父类)的属性和方法。继承的主要目的是实现代码重用,以及建立一种类型之间的层次关系。
特点
-
代码重用:子类继承了父类的属性和方法,减少了代码的重复编写。
-
扩展性:子类可以扩展父类的功能,添加新的属性和方法,或者重写(覆盖)现有的方法。
-
多态性:通过继承和虚函数,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;
}