C++拒绝疑惑脸

C++拒绝疑惑脸,第1张

关于virtual

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

        1,函数覆盖:

         

#include 

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 

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 

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/3002386.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-27
下一篇 2022-09-27

发表评论

登录后才能评论

评论列表(0条)

保存