prctise .cpp & .h 的拆分
1 #include <iostream>
2 using namespace std;
3
4 class People
5 {
6
7 public:
8
9 People(int age, char sex)
10 {
11 // cout<<"people's constructor!"<<endl;
12 }
13 ~People()
14 {
15 // cout<<"people's desconstructor!"<<endl;
16 }
17 void fight(){cout<<"People fighting~~"<<endl;}
18 void eat(){cout<<"People eat"<<endl; }
19 protected:
20 void drink(){cout<<"People drink"<<endl;}
21
22 private:
23 void sleep(){cout<<"People sleep"<<endl;}
24 };
25
26 class Man : public People
27 { public:
28 //若父类的构造函数带参数,则子类在调用父类的构造函数时会出现错误,因为父类的default constructor 已经不再存在了,.
29
30 Man():People(23,'m') ,a(1) { //no appropriate default constructor available //给基类的构造函数赋值
31 // cout<<"Man's constructor!"<<endl;
32 }
33
34 ~Man()
35 {
36 // cout<<"Man's destructor!"<<endl;
37 }
38 void fight()
39 { People::fight();
40 cout<<"Man fighting~~"<<endl;
41 } //相对于People's fight() ,Man's fight()是对它的覆盖,它是发生在父类和子类之间的,而函数的继承是发生在一个类之中的
42
43 void test()
44 {
45 drink();
46 // sleep(); //cannot access private member declared in class 'People'
47 }
48 private:
49 const int a;
50 };
51
52
53 void main()
54 {
55 // People man;
56 // man.eat();
57 Man zhangsan;
58 zhangsan.fight();
59 //zhangsan.eat();
60
61
62 //zhangsan.drink(); //cannot access protected member declared in class 'People'
63 //fangping.drink(); //cannot access private member declared in class 'People'
64 //fangping.sleep(); //cannot access protected member declared in class 'People'
65 }
66
2 using namespace std;
3
4 class People
5 {
6
7 public:
8
9 People(int age, char sex)
10 {
11 // cout<<"people's constructor!"<<endl;
12 }
13 ~People()
14 {
15 // cout<<"people's desconstructor!"<<endl;
16 }
17 void fight(){cout<<"People fighting~~"<<endl;}
18 void eat(){cout<<"People eat"<<endl; }
19 protected:
20 void drink(){cout<<"People drink"<<endl;}
21
22 private:
23 void sleep(){cout<<"People sleep"<<endl;}
24 };
25
26 class Man : public People
27 { public:
28 //若父类的构造函数带参数,则子类在调用父类的构造函数时会出现错误,因为父类的default constructor 已经不再存在了,.
29
30 Man():People(23,'m') ,a(1) { //no appropriate default constructor available //给基类的构造函数赋值
31 // cout<<"Man's constructor!"<<endl;
32 }
33
34 ~Man()
35 {
36 // cout<<"Man's destructor!"<<endl;
37 }
38 void fight()
39 { People::fight();
40 cout<<"Man fighting~~"<<endl;
41 } //相对于People's fight() ,Man's fight()是对它的覆盖,它是发生在父类和子类之间的,而函数的继承是发生在一个类之中的
42
43 void test()
44 {
45 drink();
46 // sleep(); //cannot access private member declared in class 'People'
47 }
48 private:
49 const int a;
50 };
51
52
53 void main()
54 {
55 // People man;
56 // man.eat();
57 Man zhangsan;
58 zhangsan.fight();
59 //zhangsan.eat();
60
61
62 //zhangsan.drink(); //cannot access protected member declared in class 'People'
63 //fangping.drink(); //cannot access private member declared in class 'People'
64 //fangping.sleep(); //cannot access protected member declared in class 'People'
65 }
66