C++拒绝疑惑脸

关于virtual

         virtual一般用来修饰函数,这样的函数被称为“虚函数”,虚函数用来使基类指针指向派生类对象时(派生类和基类中的成员函数名称和基类的成员函数名相同),能够准确地调用派生类中的成员函数。

        1,函数覆盖:

         

#include <iostream>

using namespace std;

class Animal
{
public:
    virtual void eat() // 虚函数
    {
        cout << "动物能吃东西" << endl;
    }
};

class Cat:public Animal
{
public:
    void eat() // 虚函数
    {
        cout << "猫能吃鱼" << endl;
    }
};

int main()
{
    Cat c;
    c.eat();

    return 0;
}

注意:虚函数具有继承特性,如果基类中是虚函数,那么派生类中也是虚函数,派生类中不需要用virtual关键字,也是虚函数。

2,多态的使用:

#include <iostream>

using namespace std;

class Animal
{
public:
    virtual void eat() // 虚函数
    {
        cout << "动物能吃东西" << endl;
    }
};

class Cat:public Animal
{
public:
    void eat() // 虚函数
    {
        cout << "猫能吃鱼" << endl;
    }
};

class Dog:public Animal
{
public:
    void eat()
    {
        cout << "狗吃骨头" << endl;
    }
};

/**
 * @brief test_eat1
 * @param a 基类引用派生类对象
 */
void test_eat1(Animal& a)
{
    a.eat();
}

/**
 * @brief test_eat2
 * @param a 基类指针指向派生类对象
 */
void test_eat2(Animal* a)
{
    a->eat();
}


int main()
{
    Animal a1;
    Cat c1;
    Dog d1;
    test_eat1(a1);
    test_eat1(c1);
    test_eat1(d1);

    Animal* a2 = new Animal;
    Cat* c2 = new Cat;
    Dog* d2 = new Dog;
    test_eat2(a2);
    test_eat2(c2);
    test_eat2(d2);

    delete a2;
    delete c2;
    delete d2;

    return 0;
}

3,虚析构函数:

        如果通过基类引用或指针指向派生类对象,当使用delete销毁对象时,只会调用基类的析构函数,不会调用派生类的构造函数。此时,如果派生类中有new申请的内存资源,那么会导致内存泄漏。

#include <iostream>

using namespace std;

class Animal
{
public:
    virtual void eat() // 虚函数
    {
        cout << "动物能吃东西" << endl;
    }

    virtual ~Animal()
    {
        cout << "Animal的析构函数" << endl;
    }
};

class Cat:public Animal
{
public:
    void eat()
    {
        cout << "猫能吃鱼" << endl;
    }

    ~Cat()
    {
        cout << "Cat的析构函数" << endl;
    }
};


int main()
{
    // 触发多态
    Animal* a = new Cat;
    a->eat();
    // 销毁
    delete a;

    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值