#include <iostream><br />#include <string><br />using namespace std;<br />class A<br />{<br />public:<br />A()<br />{<br />cout << "creat A" << endl;<br />scc();<br />}<br />virtual void scc()<br />{<br />cout << "scc from A" << endl;<br />}<br />virtual ~A()<br />{<br />cout << "delete A" << endl;<br />}<br />private:<br />int i;<br />};<br />class C<br />{<br />public:<br />C()<br />{}<br />int virtual c()<br />{<br />return 0;<br />}<br />};<br />class B : public A, public C<br />{<br />public:<br />B()<br />{<br />cout << "creat B" << endl;<br />scc();<br />}<br />void scc()<br />{<br />cout << "scc from B" << endl;<br />}<br />void virtual socket()<br />{<br />cout << "socket ..." << endl;<br />}<br />~B()<br />{<br />cout << "delete B" << endl;<br />}<br />};<br />int main(int argc, char **argv)<br />{<br /> A *b = new B;<br />cout << "Hello!" << endl;<br />cout << sizeof(A) << sizeof(B) << sizeof b << endl;<br />delete b;<br />return 0;<br />}
輸出:
creat A<br />scc from A<br />creat B<br />scc from B<br />Hello!<br />8124<br />delete B<br />delete A<br />
- 如果沒有顯式調用delete b 則解構函式不執行
- 雖然每個類有兩個虛函數,但是他們存在一個虛函數表中,並且只有一個指向此表的指標!多繼承時有多指標(不管衍生類別是否覆蓋了父類的虛函數),子類定義新的虛函數,存在原來的虛表中,不會增加一個指標。
- 父類的資料成員影響子類的sizeof
- sizeof 是運算式,不是函數,它只記健中的佔用空間,static和普通函數不算的!當運算式是變數名時,可以不用()
問題:新的虛函數存在那個父類的虛表中????
#include <iostream><br />#include <string><br />#include <cstring> //c風格字元strcpy等。。<br />using namespace std;<br />class A<br />{<br />public:<br />A()<br />{<br />cout << "creat A" << endl;<br />scc(); //構造時,基類建構函式只會調用基類的函數,即使是虛函數也是如此!!<br />}<br />virtual void scc()<br />{<br />cout << "scc from A" << endl;<br />}<br />virtual ~A()<br />{<br />cout << "delete A" << endl;<br />}<br />private:<br />int i;<br />};<br />class C<br />{<br />public:<br />C()<br />{<br />cout << "creat C" << endl;<br />}<br />int virtual c()<br />{<br />return 0;<br />}<br />};<br />class B : public A, public C<br />{<br />public:<br />B() : s("ppp")<br />{<br />cout << "creat B" << endl;<br />scc();<br />}<br />void scc()<br />{<br />cout << "scc from B" << endl;<br />}<br />void virtual socket()<br />{<br />cout << "socket ..." << endl;<br />cc = new char[100];<br />strcpy(cc, "who are you?");<br />strcpy(cc + strlen(cc), "lll"); //用strcpy作strcat.....<br />s += (cc + 1); //pppho are you? (cc+1)事實上是從第二個字元開始的一個串。。使用這個辦法可以進行字串的串連!<br />cout << s << endl;<br />}<br />~B()<br />{<br />cout << "delete B" << endl;<br />}<br />private:<br />string s;<br />char *cc;<br />//char cc[] = "Hello"; //編譯錯誤,類定義時不能初始化??<br />};<br />int main(int argc, char **argv)<br />{<br />A *b = new B; //必須手動delete才調用析構<br />B bb; //自動調用析構<br />cout << "Hello!" << endl;<br />cout << sizeof(A) << sizeof(B) << sizeof b << endl;<br />//b->socket(); //編譯錯誤:‘class A’ has no member named ‘socket’!是否可以強制編譯那??b到底應該看作A還是B類????<br />bb.socket();<br />delete b;<br />return 0;<br />}