C++:C++的两种多态形式
1 //
2 // main.cpp
3 // Test.cpp
4 //
5 // Created by mac on 15/8/11.
6 // Copyright (c) 2015年. All rights reserved.
7 //
8 #include<iostream>
9 #include<cstring>
10 using namespace std;
11 class Person //基类Person
12 {
13 private:
14 string name;
15 int age;
16 public:
17 Person();
18 virtual ~Person();//虚析构函数
19 Person(string name,int age);
20 void setname(string name);
21 void setage(int age);
22 virtual void show();//虚成员函数,子类继承后必须要重写该函数
23 //virtual void show()=0;//纯虚函数,此时该类就不能创建对象了。
24 };
25 Person::Person(){};
26 Person::Person(string name,int age)
27 {
28 this->name = name;
29 this->age = age;
30 }
31 void Person::setname(string name)
32 {
33 this->name = name;
34 }
35 void Person::setage(int age)
36 {
37 this->age = age;
38 }
39 void Person::show()
40 {
41 cout<<"name:"<<name<<","<<"age:"<<age<<endl;
42 }
43 Person::~Person(){};
47 class Student:public Person//基类Person的公有派生类Studnet
48 {
49 private:
50 float score;
51 string subject;
52 public:
53 Student();
54 virtual ~Student();//virtual可加可不加
55 virtual void show();//virtual可加可不加
56 Student(string name,int age,float score,string subject);
57 };
58 Student::Student(){};
59 Student::Student(string name,int age,float score,string subject):Person(name,age)
60 {
61 this->score = score;
62 this->subject = subject;
63 }
64 void Student::show()
65 {
66 Person::show();
67 cout<<"score:"<<score<<","<<"subject:"<<subject<<endl;
68 }
69 Student::~Student(){};
70 int main(int argc, const char * argv[])
71 {
72 Person p;
73 p.setname("xiayuanquan");
74 p.setage(23);
75 p.show();
76
77 Student stu("lisi",23,98.5,"English");
78 stu.show();
79
80 //多态的特性(例1)父类的引用指向子类对象
81 Person person;
82 Student st("chenglong",60,99,"chinese");
83 person = st;
84 st.show();
85
86 //多态的特性(例2)父类的指针指向子类对象
87 Person *p2 = new Student("zhangsan",20,100,"math");
88 p2->show();
89
90 return 0;
91 }
程序运行结果:
name:xiayuanquan,age:23
name:lisi,age:23
score:98.5,subject:English
name:chenglong,age:60
score:99,subject:chinese
name:zhangsan,age:20
score:100,subject:math
Program ended with exit code: 0
总结:实现多态的三个条件:
1.存在继承关系
2.多态的第一种,父类的引用指向子类对象 或者 多态的第二种,父类的指针指向子类对象。
3.子类必须要重写父类的同名方法
程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式!