c++笔记——类的继承、多态、虚函数、纯虚函数

主要的测试类

//测试纯虚函数的用法
class  Animal{
public:
    Animal() = default;
    ~Animal() = default;

    virtual string color() = 0;

    static bool eat();
};

bool Animal::eat() {
    return true;
}

class Cat : public Animal{
public:
    Cat() = default;
    ~Cat() = default;

    int a = 0;
};

class Dog:public Animal{
public:
    Dog() = default;
    ~Dog()= default;
    string color() override{
        return "yellow";
    }
};


//测试带指针的类的析构
class Base{
public:
    Base() : a(new int(10)){
        cout <<"this is a base contor." << endl;
    }

    virtual ~Base(){
        delete a;
        cout << "this is a base dector" << endl;
    }

    virtual void do_something(){
        cout << "base class do some thing.." << endl;
    }

private:

    int* a;

};

class Derived:public  Base{
public:
    Derived(): b(new int(20)){
        cout << "this is a derived contor." << endl;
    }

    ~Derived() override {
        delete b;
        cout << "this is a derived dector." << endl;

    }
    void do_something() override {
        cout << "derived class do some thing.." << endl;
    }

    void do_dervied_thing(){
        cout << "do derived thing in derived class." << endl;
    }

private:
    int* b;

};

 

测试代码:

void virtual_class_test(){
   //Animal a;// error: cannot declare variable ‘a’ to be of abstract type ‘Animal’
//   Cat a;//error: cannot declare variable ‘a’ to be of abstract type ‘Cat’   没有定义虚函数,仍然是一个纯虚函数,抽象类不能被实例化

    Dog d;
    Animal* a = new Dog;//可以定义个基类的指针,来指向派生类的对象
    Animal& aa(d);//可以定义个基类的引用,来指向派生类的对象

/*    {
        Base ba;
    }*/

/*    {
        Derived da;//先构造基类,再构造派生类,先析构派生类,再析构基类
    }*/

    {
      //  Derived* da = new Base;// error: conversion from ‘Base*’ to non-scalar type ‘Derived’ requested
    }

    int num[3] = {1,2,3};

    {
        Base* ba = new Derived;//先构造基类,再构造派生类,但是没有析构函数
        ba->do_something();//调用派生类的函数,实现多态
        delete ba;//需要手动释放指针对象
        cout << "*******************" << endl;
    }

    {
        std::unique_ptr<Base> ba = make_unique<Derived>();
        ba->do_something();
        //不需要手动释放指针,在没加析构函数的虚函数时,只调用基类的虚函数,会造成内存泄露
        //ba也调用不到dervied中do_dervied_thing函数
    }

}

 

posted @ 2023-04-23 14:58  水水滴答  阅读(6)  评论(0编辑  收藏  举报