虚函数详解

本文详细解释了C++中虚函数的使用,通过基类指针调用派生类定义的函数,展示了多态和动态绑定的概念,以及在不同类实例中的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

虚函数使用意义:通过基类访问派生类定义的函数

#include <iostream>

class fruit
{
private:
    /* data */
public:
    fruit(/* args */);
    virtual ~fruit();
    virtual void print() {std::cout << "this fruit print " << std::endl;}
};

fruit::fruit(/* args */)
{
}

fruit::~fruit()
{
    std::cout << "fruit ~~" << std::endl;
}

class shape
{
private:
    /* data */
public:
    shape(/* args */);
    ~shape();
    void print() {std::cout << "this shape print " << std::endl;}
};

shape::shape(/* args */)
{
}

shape::~shape()
{
    std::cout << "shape ~~" << std::endl;
}

class apple : public fruit
{
private:
    /* data */
public:
    apple(/* args */);
    ~apple();
    void print() {std::cout << "this apple print " << std::endl;}
};

apple::apple(/* args */)
{
}

apple::~apple()
{
    std::cout << "apple ~~" << std::endl;
}

class circle :public shape
{
private:
    /* data */
public:
    circle(/* args */);
    ~circle();
    void print() {std::cout << "this circle print " << std::endl;}
};

circle ::circle(/* args */)
{
}

circle ::~circle()
{
    std::cout << "circle ~~" << std::endl;
}

int main()
{
    apple *pApple = new apple;
    // cout << "---" << endl;
    pApple->print();
    delete pApple;
    std::cout << std::endl;

    fruit *pfruit = new apple;
    pfruit->print();
    delete pfruit;
    std::cout << std::endl;

    circle *pCircle = new circle;
    pCircle->print();
    delete pCircle;
    std::cout << std::endl;

    shape *pshape = new circle;
    pshape->print();
    delete pshape;
    return 0;
}

运行结果:

this apple print 
apple ~~
fruit ~~

this apple print 
apple ~~
fruit ~~

this circle print 
circle ~~
shape ~~

this shape print 
shape ~~

参考文章:

C++虚函数详解-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值