虚函数签名不匹配及其行为

Virtual Function Signature Mismatch and its behavior

我正在查看虚函数行为的示例。鉴于此测试代码,我对其行为有一些疑问。

class A
{
public:
    A(int x)
    {
        cout << "In A Constructor" << endl;
        print();
    }
    ~A(){
        cout << "In A Destructor" << endl;
        delete _val;
    }
    virtual void print() { cout << "A." << endl; }
private:
    char* _val;
};

class B: public A
{
public:
    B(int x, int y) : A(x)
    {
        _dVal = new char[y];
        cout << "In B Constructor 1" << endl;
        print();
    }
    B() : A(0)
    {
        _dVal = new char[1];
        cout << "In B Constructor 2" << endl;
        print();
    }
    ~B(){
        cout << "In B Destructor" << endl;
        delete _dVal;
    }
    void print() { cout << "B" << endl; }
private:
    char* _dVal;
};

int main(int argc, char** argv) {
    A* p1 = new B();
    p1->print();
    delete p1;
    return 0;
}

输出为:

In A Constructor
A.
In B Constructor 2
B
B
In A Destructor

1) 如果 class A 是唯一表示它为虚函数的函数,并且它是通过取消引用 (->) 调用的,为什么要为 class B 调用 print? 2) 为什么 B 的析构函数从未被调用,如果实际上正在调用构造函数?

1) Why is print called for class B if class A is the only one denoting it as a virtual function and it is being called by dereference (->)?

这就是虚函数应该做的。指针 p1A* 类型,但它实际上指向 B 类型的对象。并且这种动态绑定仅在使用指针或对基 class.

的引用处理派生 class 时发生

另请注意,派生的 class 中的覆盖函数也是 virtual(无论其声明中是否使用关键字 virtual)。

2) Why is the destructor for B never being called if the constructor is in fact being called?

未调用 B 的析构函数,因为您没有将基 class(即 A::~A)的析构函数声明为 virtual destructor。这种情况下的行为是未定义的。调用 B 的构造函数是因为您通过 new B().

显式构造了 B