c++虚函数指的是什么

c++
1209
2023/11/16 12:22:20
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

C++的虚函数是一种特殊的成员函数,用于实现多态。多态是面向对象编程的一个重要特性,它允许以统一的方式处理不同类型的对象。

虚函数通过在基类中声明并在派生类中重新定义,实现了动态绑定(也称为运行时多态)。当基类指针或引用指向派生类对象时,通过调用虚函数,可以根据实际的派生类类型来确定要执行的函数。

虚函数的声明格式如下:

virtual 返回类型 函数名(参数列表) [const] = 0;

其中,virtual关键字表示虚函数,= 0表示该虚函数是纯虚函数,需要在派生类中重新定义,而不能在基类中实现。

通过使用虚函数,可以实现类似于以下的多态行为:

class Animal {
public:
    virtual void makeSound() {
        cout << "Animal makes sound." << endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        cout << "Dog barks." << endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        cout << "Cat meows." << endl;
    }
};

int main() {
    Animal* animal1 = new Dog();
    Animal* animal2 = new Cat();

    animal1->makeSound();  // 输出 "Dog barks."
    animal2->makeSound();  // 输出 "Cat meows."

    delete animal1;
    delete animal2;

    return 0;
}

在上述示例中,Animal类中的makeSound()函数被声明为虚函数。通过使用基类指针分别指向派生类对象,调用makeSound()函数时,根据实际的派生类类型来确定执行的函数。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C++ stoll如何转换大数字符串