# C++多态和虚函数

1304人阅读 评论(0)

## 多态的实现

//student.h
#include <iostream>
using namespace std;
class student
{
public:
student(char *n,int a,int h,int w);
student();
void set(char *n,int a,int h,int w);
char * sname();
int sage();
int sheight();
int sweight();
virtual void study();//把学习设置为虚函数
protected:
char name[10];
int age;
int height;
int weight;
};
char * student::sname()
{
return name;
}
int student::sage()
{
return age;
}
int student::sheight()
{
return height;
}
int student::sweight()
{
return weight;
}
void student::set(char *n,int a,int h,int w)
{
int i;
for (i=0;n[i]!='\0';i++)
{
name[i]=n[i];
}
name[i]='\0';
age=a;
height=h;
weight=w;
return;
}
student::student(char *n,int a,int h,int w)
{
cout <<"Constructing a student with parameter..." <<endl;
set(n,a,h,w);
}
student::student()
{
cout <<"Constructing a student without parameter..." <<endl;
}
void student::study()//成员函数定义处没有virtual
{
cout <<"随便学些什么。" <<endl;
return;
}
#include "student.h"
{
public:
double score();
void setGPA(double g);
virtual void study();//把学习设置为虚函数
protected:
double GPA;
};
{
return GPA;
}
{
GPA=g;
return;
}
{
return age>=18?true:false;
}
{
cout <<"学习高等数学和大学英语。" <<endl;
return;
}
//pupil.h
class Pupil:public student
{
public:
virtual void study();//把学习设置为虚函数
};
void Pupil::study()
{
cout <<"学习语数外。" <<endl;
return;
}
//main.cpp
#include <iostream>
#include "pupil.h"
using namespace std;
int main()
{
student s2;
Pupil s3;
student *sp=&s1;//sp指向本科生对象
s1.set("Tom",21,178,60);
sp->study();//体现多态性
sp=&s2; //sp指向学生对象
s2.set("Jon",22,185,68);
sp->study();//体现多态性
sp=&s3; //sp指向小学生对象
s3.set("Mike",8,148,45);
sp->study();//体现多态性
return 0;
}

Constructing a student without parameter...
Constructing a student without parameter...
Constructing a student without parameter...

## 无法实现多态的虚函数

//student.h
#include <iostream>
using namespace std;
class student
{
public:
student(char *n,int a,int h,int w);
student();
void set(char *n,int a,int h,int w);
char * sname();
int sage();
int sheight();
int sweight();
virtual void study(int c=0);//设置为虚函数，带默认参数
protected:
char name[10];//姓名
int age;//年龄
int height;//身高
int weight;//体重
};
……
void student::study(int c)
{
cout <<"随便学些什么。" <<endl;
return;
}
//main.cpp
#include <iostream>
#include "pupil.h"
using namespace std;
int main()
{
student s2;
Pupil s3;
student *sp=&s1;
s1.set("Tom",21,178,60);
sp->study(1);//带参数
sp=&s2;
s2.set("Jon",22,185,68);
sp->study();
sp=&s3;
s3.set("Mike",8,148,45);
sp->study();
return 0;
}

Constructing a student without parameter...
Constructing a student without parameter...
Constructing a student without parameter...

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：1551778次
• 积分：14849
• 等级：
• 排名：第767名
• 原创：198篇
• 转载：105篇
• 译文：2篇
• 评论：280条
最新评论