#include <iostream>
using namespace std;
class Base{
public:
~Base() {
cout << "base destructor" << endl;
}
};
class Derived: public Base {
public:
~Derived() {
cout << "derived constructor" << endl;
}
};
int main(int argc, const char* argv[]) {
{
Derived d;
}
cout << "=========" << endl;
Base *b = new Derived;
delete b;
return 0;
}
執行結果為:
derived constructor
base destructor
=========
base destructor
#include <iostream>
using namespace std;
class Base{
public:
virtual ~Base() { // 這裡加上 virtual
cout << "base destructor" << endl;
}
};
class Derived: public Base {
public:
~Derived() {
cout << "derived constructor" << endl;
}
};
int main(int argc, const char* argv[]) {
{
Derived d;
}
cout << "=========" << endl;
Base *b = new Derived;
delete b;
return 0;
}
執行結果為:
derived constructor
base destructor
=========
derived constructor
base destructor
...
No comments:
Post a Comment