C++语言:
01 /* 02 对象切片 03 此处为传值 注意与传地址相比较 04 */ 05 #include <iostream> 06 #include <string> 07 using namespace std; 08 09 class Pet 10 { 11 string pname; 12 public : 13 Pet( const string & name) 14 : pname( name) 15 {} 16 virtual string name() const 17 { 18 return pname; 19 } 20 virtual string description() const 21 { 22 return "This is " + pname; 23 } 24 }; 25 26 class Dog : public Pet 27 { 28 string favoriteActivity; 29 public : 30 Dog( const string & name , const string & activity) 31 : Pet( name ), favoriteActivity( activity) 32 {} 33 string description() const 34 { 35 return Pet :: name() + " likes to " + 36 favoriteActivity; 37 } 38 }; 39 40 void describe( Pet p) 41 { 42 cout << p . description() << endl; 43 } 44 45 int main() 46 { 47 Pet p( "Alfred"); 48 Dog d( "Fluffy" , "sleep"); 49 describe(p); 50 describe( d); 51 52 return 0; 53 } 54 /* 55 This is Alfred 56 This is Fluffy 57 58 Process returned 0 (0x0) execution time : 0.070 s 59 Press any key to continue. 60 61 */
C++语言:
01 /* 02 地址传递 03 启用虚函数机制 04 */ 05 #include <iostream> 06 #include <string> 07 using namespace std; 08 09 class Pet 10 { 11 string pname; 12 public : 13 Pet( const string & name) 14 : pname( name) 15 {} 16 virtual string name() const 17 { 18 return pname; 19 } 20 virtual string description() const 21 { 22 return "This is " + pname; 23 } 24 }; 25 26 class Dog : public Pet 27 { 28 string favoriteActivity; 29 public : 30 Dog( const string & name , const string & activity) 31 : Pet( name ), favoriteActivity( activity) 32 {} 33 string description() const 34 { 35 return Pet :: name() + " likes to " + 36 favoriteActivity; 37 } 38 }; 39 40 void describe( Pet * p) 41 { 42 cout << p -> description() << endl; 43 } 44 45 int main() 46 { 47 Pet * p = new Pet( "Alfred"); 48 Dog * d = new Dog( "Fluffy" , "sleep"); 49 describe(p); 50 describe( d); 51 52 return 0; 53 } 54 /* 55 This is Alfred 56 Fluffy likes to sleep 57 58 Process returned 0 (0x0) execution time : 0.059 s 59 Press any key to continue. 60 61 62 63 */