1.虚析构函数
class MM { public: virtual void print() { cout << "MM" << endl; } virtual ~MM() { cout << "~MM" << endl; } }; class Girl:public MM { public: void print() { cout << "Girl" << endl; } ~Girl() { cout << "~Girl" << endl; } }; int main() { //下面的无名Girl对象没有被释放 MM* pmm = new Girl; pmm->print(); //Girl //加了virtual打印 ~Girl delete pmm; //~MM return 0; }
2.dynamic_cast
作用:上行转换、下行转换、交叉转换
class A { public: virtual void print() { cout << "A" << endl; } }; class B { public: virtual void print() { cout << "B" << endl; } }; class C :public A, public B { public: void print() { cout << "C" << endl; } }; void test() { //子类对象初始化父类指针 A* pa = new C; B* pB = dynamic_cast<B*>(pa); pB->print(); //C } int main() { test(); return 0; }