c++类多态

c++类多态

定义:同一操作或者函数,在不同对象上的表现

常见问题:

1、c++构造函数可不可以是虚函数,析构函数可不可以是虚函数

  • 无论何种场景,构造函数不可能是虚函数

  • 析构函数可以是虚函数,析构函数为虚函数经常是在类的多态中使用;或者说多态中,基类析构函数必须为虚函数

2、析构函数可不可以是,纯虚函数

  • 可以,但不常用,且必须在类外再次定义析构函数

  • 无论是析构函数为纯虚函数,或者是其他函数为纯虚函数,类变成了抽象类,不允许实例化

3、多态构造和析构顺序,基类开始,最后一个析构也是基类,参考栈

示例代码

#include <iostream>

class Base {
public:
    Base() {
        std::cout << "Base Constructor\n";
    }
    virtual ~Base() { // 如果这个析构函数不是虚函数,将会引发问题
        std::cout << "Base Destructor\n";
    }
    virtual void show() = 0; // 纯虚函数声明
};

class Derived : public Base {
public:
    Derived() {
        std::cout << "Derived Constructor\n";
    }
    ~Derived() {
        std::cout << "Derived Destructor\n";
    }

    void show() override {
        std::cout << "===" << std::endl;
    }
};

int main() {
    Base* obj = new Derived();
    obj->show();
    delete obj; // 如果 Base 的析构函数不是虚函数,只会调用 Base 的析构函数
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中的多态性是面向对象编程的一个重要概念,它允许使用基的指针或引用来调用派生的方法。C++中的多态性可以通过两种方式实现:多态和函数多态。 1. 多态多态是通过继承和虚函数来实现的。当基的指针或引用指向派生的对象时,可以通过虚函数来调用派生中的方法。这种调用方式是动态绑定的,即在运行时确定调用的是哪个方法。这种动态绑定是通过虚函数表和虚函数表指针来实现的[^1]。 范例: ```cpp #include <iostream> class Shape { public: virtual void draw() { std::cout << "Drawing a shape." << std::endl; } }; class Circle : public Shape { public: void draw() override { std::cout << "Drawing a circle." << std::endl; } }; class Rectangle : public Shape { public: void draw() override { std::cout << "Drawing a rectangle." << std::endl; } }; int main() { Shape* shape1 = new Circle(); Shape* shape2 = new Rectangle(); shape1->draw(); // 输出:Drawing a circle. shape2->draw(); // 输出:Drawing a rectangle. delete shape1; delete shape2; return 0; } ``` 2. 函数多态: 函数多态是通过函数重载和模板来实现的。函数重载允许在同一个作用域中定义多个同名函数,但它们的参数型或个数不同。当调用这些同名函数时,编译器会根据实参的型或个数来选择合适的函数进行调用。这种调用方式是静态绑定的,即在编译时确定调用的是哪个函数。模板是一种通用的函数或,它可以根据实参的型自动生成对应的函数或。 范例: ```cpp #include <iostream> void print(int num) { std::cout << "Printing an integer: " << num << std::endl; } void print(double num) { std::cout << "Printing a double: " << num << std::endl; } template <typename T> void print(T value) { std::cout << "Printing a value: " << value << std::endl; } int main() { print(10); // 输出:Printing an integer: 10 print(3.14); // 输出:Printing a double: 3.14 print("Hello"); // 输出:Printing a value: Hello return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值