我有两个类,而B
派生A
.
我创建了一个指向 的指针A
,称为:a2
。请看看我的main
功能。
这条线有什么作用?
a2 = new B();
为什么当我 delete 时a2
,只有 A 的析构函数被激活?
#include <iostream>
using namespace std;
class A {
int num;
public:
A() { cout << "constructor of A\n"; }
void set_num(int new_num) { cout << "set_num of A" << endl; num = new_num; }
void print() { cout << "print of A: "; cout << num << endl; }
~A() { cout << "destructor of A\n"; }
};
class B: public A {
int num;
public:
B() { cout << "constructor of B\n"; }
void set_num(int new_num) { cout << "set_num of B" << endl; num = new_num; }
void print() { cout << "print of B: "; cout << num << endl; }
~B() { cout << "destructor of B\n"; }
};
void main() {
A *a2;
a2 = new B();
delete a2;
}
这是输出:
constructor of A
constructor of B
destructor of A
每个帮助表示赞赏!