c++多態多實例

#include <bits/stdc++.h>
using namespace std; class A { public: A() { cout << "構造A" << endl; s = new char[20]; memset(s, 0, 20); strcpy(s, "hahaha"); } virtual ~A() { cout << "析構A" << endl; delete []s; } virtual void print() { cout << s << endl; } private: char *s; }; class B :  public A { public: B() { cout << "構造B" << endl; s = new char[20]; memset(s, 0, 20); strcpy(s, "BBBBB"); } virtual ~B() { cout << "析構B" << endl; delete []s; } virtual void print() { cout << s << endl; } private: char *s; }; void ok(A *obj) { obj->print(); } void okk(A obj) { obj.print(); }

1.c++

int main() { B *b = new B; A *obj = b; obj->print(); delete b; /*構造A 構造B BBBBB 析構B 析構A*/ }

2.函數

int main() { B *b = new B; A *obj = b; obj->print(); delete obj; /*構造A 構造B BBBBB 析構A*/ }

3.佈局

int main() { B b; A a = b; A *pa = &b; a.print();//這裏的a就是一個A類型的變量,它的內存佈局在賦值的時候已經從B轉換到A了,多於的數據都被丟棄,所以其就是一個A類型的變量。
    pa->print();//其是一個指針,其類型雖然是A,但指向的區域的內容倒是一個B類型的內存結構,雖然內存結果的佈局與A兼容,但其虛函數表中的Test倒是B的實現

    /*構造A 構造B hahaha BBBBB 析構A 析構B 析構A*/ }

4.spa

int main() { B *b = new B; ok(b); /*構造A 構造B BBBBB*/ }

5.指針

int main() { B *b = new B; ok(b); delete b; /*構造A 構造B BBBBB 析構B 析構A*/ }

6.code

int main() { B b; okk(b); /*構造A 構造B hahaha 析構A 析構B 析構A*/ }

7.對象

int main() { B *b = new B; A a; b = &a; //報錯,不能讓子類指針指向父對象
 ok(b); }
相關文章
相關標籤/搜索