class Base
{
private:
int Y;
public:
Base(int y = 0) { Y = y;cout << "Base(" << y << ")\n"; };
~Base() { cout << "~Base()\n"; };
virtual void print() { cout << Y << " "; };
};
class Derived : public Base
{
private:
int Z;
public:
Derived(int y, int z) :Base(y) { Z = z;cout << "Derived(" << y <<","<<z<<")\n"; };
~Derived() { cout << "~Derived()\n"; };
void print() { Base::print();cout << Z << endl; };
};
int main()
{
Derived d(300, 400); // Base(300) Derived(300,400)
d.print(); // 300 400
Base *a = new Derived(100, 200); // Base(100) Derived(100,200)
a->print(); // 100 200
delete a; // ~Base() 析构没有定义成virtual 所以无法调用子类的析构
{
private:
int Y;
public:
Base(int y = 0) { Y = y;cout << "Base(" << y << ")\n"; };
~Base() { cout << "~Base()\n"; };
virtual void print() { cout << Y << " "; };
};
class Derived : public Base
{
private:
int Z;
public:
Derived(int y, int z) :Base(y) { Z = z;cout << "Derived(" << y <<","<<z<<")\n"; };
~Derived() { cout << "~Derived()\n"; };
void print() { Base::print();cout << Z << endl; };
};
int main()
{
Derived d(300, 400); // Base(300) Derived(300,400)
d.print(); // 300 400
Base *a = new Derived(100, 200); // Base(100) Derived(100,200)
a->print(); // 100 200
delete a; // ~Base() 析构没有定义成virtual 所以无法调用子类的析构
// d的析构 // ~Derived() ~Base()
}