2.10 继承
2.10.1 继承基本概念
继承是面向对象编程(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
#include <iostream>
#include <string>
class Animal {
protected:
std::string name;
int age;
public:
Animal(std::string n, int a) : name(n), age(a) {}
virtual void makeSound() {
std::cout << name << " makes a sound." << std::endl;
}
virtual void display() {
std::cout << "Animal: " << name << ", Age: " << age << std::endl;
}
};
派生类:Lion
class Lion : public Animal {
public:
Lion(std::string n, int a) : Animal(n, a) {}
void makeSound() override {
std::cout << name << " roars." << std::endl;
}
void display() override {
std::cout << "Lion: " << name << ", Age: " << age << std::endl;
}
};
派生类:Elephant
class Elephant : public Animal {
public:
Elephant(std::string n, int a) : Animal(n, a) {}
void makeSound() override {
std::cout << name << " trumpets." << std::endl;
}
void display() override {
std::cout << "Elephant: " << name << ", Age: " << age << std::endl;
}
};
派生类:Bird
class Bird : public Animal {
public:
Bird(std::string n, int a) : Animal(n, a) {}
void makeSound() override {
std::cout << name << " sings." << std::endl;
}
void display() override {
std::cout << "Bird: " << name << ", Age: " << age << std::endl;
}
};
使用这些类
int main() {
Lion lion("Leo", 5);
Elephant elephant("Ella", 10);
Bird bird("Bella", 2);
lion.display();
lion.makeSound();
elephant.display();
elephant.makeSound();
bird.display();
bird.makeSound();
return 0;
}
在这个例子中:
Animal
是基类,定义了所有动物共有的属性(如name
和age
)和方法(如makeSound
和display
)。Lion
、Elephant
和Bird
是派生类,它们继承了Animal
的特性,并根据自身的特性重写了makeSound
和display
方法。- 在
main
函数中,创建了各种动物的实例,并展示了它们的行为。
这个例子展示了继承如何使代码更有组织、更易于管理,并且如何通过重写基类方法来实现多态性。