C++ 继承和多态,重写和虚函数

继承

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值