#include<iostream> class base { public: virtual ~base(){std::cout << "base\n";} }; class derived : public base { private: ~derived(){std::cout << "derived\n";} /* destructor is private */ }; int main() { base *pt= new derived; delete pt; }
解决方法
这不仅会发生在析构函数中.
#include<iostream> class base { public: virtual void x(){std::cout << "base\n";} }; class derived : public base { private: void x(){std::cout << "derived\n"; base::x();} }; int main() { base *pt= new derived; pt->x(); //OK //((derived *)pt)->x(); //error: ‘virtual void derived::x()’ is private derived *pt2= new derived; //pt2->x(); //error: ‘virtual void derived::x()’ is private ((base *)pt2)->x(); //OK }