C++: related knowledge points of classes 2

virtual function

A virtual function is a member function that defines a consistent calling interface for functions with the same name and accepting the same parameters in derived classes . When a virtual function is called, what is actually called is the function in the corresponding derived class. Defining a function with the same name and parameters as the virtual function in the base class in the derived class can cause the virtual function to be overridden (override).

class Shape(){
public:
    virtual void draw();    //virtual意味着“可以覆盖”
    virtual ~Shape() {};    //虚析构函数
    //....
};

class Circle : public Shape {
public:
    void draw();     //覆盖Shape::draw
    ~Circle();       //覆盖Shape::~Shape()
    //....
};

Roughly speaking, the virtual function in the base class (Shape in the above example) defines a calling interface for the derived class (Circle in the above example) :

void f(Shape& s)
{
    //...
    s.draw();
}

void g()
{
    Circle c(Point{0,0}, 4};
    f(c);     //将会调用Circle的draw
}

It should be noted that f() does not know about the Circle class, it only knows about Shape . A class that defines a virtual function has an extra pointer through which the overriding function can be found.
Classes that define virtual functions usually need to define virtual destructors. The desire to override base class virtual functions
can be indicated with the override suffix. eg

class Square : public Shape
public:
{
    void draw() override;    //覆盖Shape::draw
    ~Shape() override;       //覆盖Shape::~Shape()
    void silly() override;   //错误,因为Shape没有虚函数Shape::silly()
    //....
};

abstract class

An abstract class is a class that can only be used as a base class, C++ does not allow objects of abstract classes to be created.

Shape s;    //错误,Shape是抽象类

class Circle : public Shape
{
public:
    void draw();     //覆盖Shape::draw
    //...
};

Circle c(p,20);     //正确,Circle不是抽象类

The most common way to make a class abstract is to define at least one pure virtual function .
Pure virtual functions are virtual functions that must be overridden in derived classes:

class Shape{
public:
    virtual void draw() = 0;     // = 0表示“纯”
    //....
};

Another rarely used but equally effective way to define an abstract class is to declare all constructors of the class as protected.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325168976&siteId=291194637