有一个常见的c++题,就是父类和子类的构造函数和析构函数分别调用顺序:
- 父类构造函数
- 子类构造函数
- 子类析构函数
- 父类析构函数
以及父类中的函数在子类中重新实现后,父类指针指向子类后,该指针调用的函数是父类中的还是子类中的(子类的)。
 通过一个例子说明:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
class Parent {
public:
    virtual void func() {
        std::cout << "Parent." << std::endl;
    }
    Parent()
    { 
        std::cout << "Parent construct.\n" << std::endl;
    }
    ~Parent()
    { 
        std::cout << "Parent destory.\n" << std::endl;
    }
};
class Son : public Parent {
public:
    void func() {
        std::cout << "Son." << std::endl;
    }
    Son()
    {
        std::cout << "Son construct.\n" << std::endl;
    }
    ~Son()
    {
        std::cout << "Son destory.\n" << std::endl;
    }
};
int main(int argc, char* argv[]) {
    Parent *parent1 = new Parent();     // Parent construct.
    Parent *parent2 = new Son();        // Parent construct.    Son construct.
    Son *son = new Son();               // Parent construct.    Son construct.
    parent1->func();                    // Parent.
    parent2->func();                    // Son.
    son->func();                        // Son.
    delete parent1;                     // Parent destory.
    delete parent2;                     // Parent destory.
    delete son;                         // Son destory.   Parent destory.
    return 0;
}

 2024年5月11日18:39:54
 今夜偏知春气暖,虫声新透绿窗纱。



















