其他分享
首页 > 其他分享> > 利用虚函数实现动态多态性

利用虚函数实现动态多态性

作者:互联网

先看一段代码:

#include <iostream>
#include<string>
using namespace std;

class Student
{
public:
Student(int,string,float);
void display();
protected:
int num;
string name;
float score;
};

Student::Student(int n,string nam,float s)
{
num =n;name=nam;score=s;
}
void Student::display()
{
cout<<"num:"<<num<<"\nname:"<<name<<"\nscore:"<<score<<"\n\n";
}

class Graduate:public Student
{public:
Graduate(int,string,float,float);
void display();
private:
float wage;

};

Graduate::Graduate(int n,string nam,float s,float w):Student (n,nam,s),wage(w) {}

void Graduate::display()
{
cout<<"num:"<<num<<"\nname:"<<name<<"\nscore:"<<score<<"\nwage="<<wage<<"\n\n";
}
int main()
{
Student stud1(1001,"LI",87.5);
Graduate grad1(2001,"Wang",98.5,1200);
Student *p;
p=&stud1;
p->display();
p=&grad1;
p->display();
return 0;
}

输出:

num:1001
name:LI
score:87.5

num:2001
name:Wang
score:98.5


--------------------------------
Process exited after 0.4979 seconds with return value 0
请按任意键继续. . .

由此我们发现没有输出wage

所以我们利用虚函数进行改变,即在基类的display()函数中 的前面加上virtual 就可以了、

 

标签:函数,int,多态性,float,Graduate,Student,动态,display,string
来源: https://www.cnblogs.com/snkz5qing/p/14850293.html