tsaiwn@magpie handout> cat -n polymo.cpp 1 // polymo.cpp -- CopyWrong by tsaiwn@csie.nctu.edu.tw 2 #include 3 class Shape{ 4 public: 5 virtual // 把這列去掉再 run 看看 6 void draw(){ cout << "drawing\n"; } 7 }; 8 class Line: public Shape{ 9 public: 10 void draw(){ cout << "draw a line\n"; } 11 }; 12 class Circle: public Shape{ 13 public: 14 void draw(){ cout << "here is a circle\n"; } 15 }; 16 int main(){ 17 Circle * ppp; 18 Shape * fig[5]; 19 // ppp = new Shape(); // error 20 ppp = (Circle *)new Shape(); 21 ppp -> draw(); 22 ppp = (Circle *)new Line(); 23 ppp -> draw(); 24 ppp = new Circle(); 25 ppp -> draw(); 26 cout << "======" << endl; 27 fig[0] = new Line(); 28 fig[1] = new Circle(); 29 fig[2] = new Circle(); 30 fig[3] = new Line(); 31 fig[4] = new Circle(); 32 for(int k=0; k<5; k++){ 33 fig[k] -> draw(); 34 } 35 } tsaiwn@magpie handout> g++ polymo.cpp tsaiwn@magpie handout> ./a.out drawing draw a line here is a circle ====== draw a line here is a circle here is a circle draw a line here is a circle tsaiwn@magpie handout> tsaiwn@magpie handout> g++ -v Using builtin specs. gcc version 2.95.4 20020320 [FreeBSD] tsaiwn@magpie handout> g++ not-poly.cpp <== 刪掉 line 5 virtual 後 tsaiwn@magpie handout> ./a.out here is a circle here is a circle here is a circle ====== drawing drawing drawing drawing drawing tsaiwn@magpie handout> exit exit Script done on Wed Feb 25 23:30:37 2004