7
XYZ
- #include <iostream>
- using namespace std;
- class X
- {
- public:
- X() { p = new int[ 2 ]; cout << "X()\t"; }
- void f( ) { cout << "X::f()\n"; }
- #if 0
- ~X() { delete [] p; cout << "~X()\n"; } // memory leak
- #else
- virtual ~X() { delete [] p; cout << "~X()\n"; }
- #endif
- private:
- int *p;
- public:
- int a;
- };
- class Y : public X
- {
- public:
- Y() { q = new int[ 1022 ]; cout << "Y(): Y::q = " << q << "\t"; }
- ~Y() { delete [] q; cout << "~Y() "; }
- void f( ) { cout << "Y::f()\n"; }
- private:
- int *q;
- public:
- int a; // overrides X::a
- };
- int main() {
- for ( int i = 0; i < 8; i++ )
- {
- X *x = new Y;
- delete x;
- }
- X x;
- x.a = 22;
- cout << endl;
- x.f();
- cout << "x.a = " << x.a << endl;
- Y y;
- y.a = 44;
- y.X::a = 66;
- cout << endl;
- y.f();
- y.X::f();
- cout << "y.a = " << y.a << endl;
- cout << "y.X::a = " << y.X::a << endl;
- X z = y;
- cout << "z.a = " << z.a << endl;
- }
Commentaires