C++ ObjectSlicing(转)
C++语言: Codee#1208001 #include <iostream>
02 #include <string>
03 using namespace std;
04
05 class Pet {
06 string pname;
07 public:
08 Pet(const string& name):pname(name){}
09 virtual string name() const { return pname;}
10 virtual string description() const {
11 return "This is "+ pname;
12 }
13 };
14
15 class Dog:public Pet {
16 string favouriteActivity;
17 public:
18 Dog(const string& name, const string& activity)
19 :Pet(name), favouriteActivity(activity){}
20 string description() const {
21 return Pet::name()+ " likes to " +favouriteActivity;
22 }
23 };
24 //Slices the object,if using void describe(Pet& p), object slicing will not happen.
25 void describe(Pet p){
26 cout << p.description() <<endl; // p is just same as base class
27 }
28
29 int main(){
30 Pet p("Alfred");
31 Dog d("Fluffy", "sleep");
32 describe(p); //base class
33 describe(d); //object slice
34 }
02 #include <string>
03 using namespace std;
04
05 class Pet {
06 string pname;
07 public:
08 Pet(const string& name):pname(name){}
09 virtual string name() const { return pname;}
10 virtual string description() const {
11 return "This is "+ pname;
12 }
13 };
14
15 class Dog:public Pet {
16 string favouriteActivity;
17 public:
18 Dog(const string& name, const string& activity)
19 :Pet(name), favouriteActivity(activity){}
20 string description() const {
21 return Pet::name()+ " likes to " +favouriteActivity;
22 }
23 };
24 //Slices the object,if using void describe(Pet& p), object slicing will not happen.
25 void describe(Pet p){
26 cout << p.description() <<endl; // p is just same as base class
27 }
28
29 int main(){
30 Pet p("Alfred");
31 Dog d("Fluffy", "sleep");
32 describe(p); //base class
33 describe(d); //object slice
34 }
本文使用Blog_Backup未注册版本导出,请到soft.pt42.com注册。