继承
1. 子类继承父类,可以调用父类的public函数以及protected函数
2. 子类继承父类,可以重写(override)父类的public函数以及protected函数
3. 单纯的继承(不涉及虚函数),子类重写的函数只在子类有效,不影响父类
#include <iostream>
using namespace std;
// 父类
class Vehicle {
public:
void drive() {
cout << "This is a generic method to describe how a vehicle drives." << endl;
}
};
// 子类 Car 继承自父类 Vehicle
class Car : public Vehicle {
public:
void drive() override {
cout << "A car drives on the road with four wheels." << endl;
}
};
int main() {
Vehicle vehicle;
Car car;
vehicle.drive(); // 输出:This is a generic method to describe how a vehicle drives.
car.drive(); // 输出:A car drives on the road with four wheels.
return 0;
}
多态(虚函数)
1. 多态是通过虚函数来实现的;
2. 多态可以理解为,子类继承父类后,对父类的某个虚函数(virtual修饰)进行重写,当对父类以如下方式基于某子类new的时候,该子类对某函数的重写会覆盖到父类的该函数。
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle" << endl;
}
};
class Square : public Shape {
public:
void draw() override {
cout << "Drawing a square" << endl;
}
};
int main() {
Shape* shape1 = new Circle();
Shape* shape2 = new Square();
shape1->draw(); // Drawing a circle
shape2->draw(); // Drawing a square
delete shape1;
delete shape2;
return 0;
}