多态性与虚函数一、多态性派生类对象可以替代基类对象为基类的引用初始化或赋值。函数的多态性其实就是对函数不同形式的声明的一种灵活应用。比如说,我们同名不同参数的函数就是对函数的一种多态性表现;同名同参就是函数的覆盖;如果我们用不同类型的参数和个数来声明不同或相同的函数,那么程序会根据我们调用实参的个数和类型进行匹配调用之前声明的函数模型,进行运算求值。二、虚函数在类的继承层次结构中,在不同的层次中可以出现同名同参(类型、个数)都相同的函数。在子类中调用父类的成员方法,可以使用子类对象调用时使用父类的作用域实现。虚函数的作用是允许在派生类中重新定义与基类同名的函数,并且可以通过基类指针或引用来访问基类和派生类中的同名函数。举一个实例来说明使用虚函数与不使用虚函数的区别,基类和派生类中都有同名函数。不使用虚函数:
- //
- // Student.h
- // Programs
- //
- // Created by bo yang on 4/17/12.
- // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
- //
-
- #ifndef Programs_Student_h
- #define Programs_Student_h
- using namespace std;
-
- class Student
- {
- public:
- Student(int ,string,float);
- void display();
- protected:
- int num;
- string name;
- float score;
- };
-
-
- #endif
- //
- // Student.cpp
- // Programs
- //
- // Created by bo yang on 4/17/12.
- // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
- //
-
- #include <iostream>
- #include <string>
- #include "Student.h"
- using namespace std;
-
- //定义构造函数
- Student::Student(int n,string nam,float s)
- {
- num=n;
- name=nam;
- score=s;
- }
-
- void Student::display()
- {
- cout<<"num:"<<num<<"
name:"<<name<<"
score:"<<score<<"
"<<endl;
- }
- //
- // Graduate.h
- // Programs
- //
- // Created by bo yang on 4/17/12.
- // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
- //
-
- #ifndef Programs_Graduate_h
- #define Programs_Graduate_h
- #include "Student.h"
- #include <string.h>
- using namespace std;
-
- class Graduate:public Student
- {
- public:
- Graduate(int ,string ,float,float);
- void display();
- private:
- float pay;
- };
-
-
- #endif
- //
- // Graduate.cpp
- // Programs
- //
- // Created by bo yang on 4/17/12.
- // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
- //
-
- #include <iostream>
- #include "Graduate.h"
- #include "Student.h"
- using namespace std;
-
- void Graduate::display()
- {
- cout<<"num:"<<num<<"
name:"<<name<<"
score:"<<score<<"
pay="<<pay<<endl;
-
- }
-
- Graduate::Graduate(int n,string nam,float s,float p):Student(n,nam,s),pay(p)
- {
-
- }
- //
- // main.cpp
- // Student&Graduate
- //
- // Created by bo yang on 4/17/12.
- // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
- //
-
- #include <iostream>
- #include "Student.h"
- #include "Graduate.h"
- using namespace std;
-
- int main(int argc, const char * argv[])
- {
-
- Student s1(1000,"David",100);
- Graduate g1(2000,"Jarry",50,20);
-
- Student *p=&s1;
- p->display();
-
- p=&g1;
- p->display();
- return 0;
- }