对象切片与虚函数机制

C++语言: Codee#25744
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++语言: Codee#25745
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 */

转载于:https://www.cnblogs.com/invisible/archive/2012/03/08/2384841.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值