菜鸟问题,大侠进来解释一下下。

逍遥_WX 2002-04-01 04:17:57
#include <iostream.h>
#include <stdlib.h>
class student
{
public:
float Cal_Grade(int tempGrade)
{
return tempGrade;
}
};
class graduate:public student
{
public:
float Cal_Grade(int tempGrade)
{
return 30+tempGrade*0.7;
}
};
float fn(student &x,int tempGrade)
{
return x.Cal_Grade(tempGrade);
}
int main()
{
student s;
graduate gs;
cout<<"The grade of s="<<s.Cal_Grade(80)<<endl;
cout<<"The grade of gs="<<gs.Cal_Grade(80)<<endl;
cout<<"The grade of s="<<fn(s,80)<<endl;
cout<<"The grade of gs="<<fn(gs,80)<<endl;

system("PAUSE");
return 0;
}

运行结果为:
The grade of s=80
The grade of gs=86
The grade of s=80
The grade of gs=80----------------这一个结果不懂,请大侠解释一下。
...全文
23 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
winfit 2002-04-01
  • 打赏
  • 举报
回复
这就是类的多态性,调用的参数虽然是graduate ,但函数的指针为student,所以调用的是它的基类,而不是graduate
wlz47 2002-04-01
  • 打赏
  • 举报
回复
float fn(student &x,int tempGrade)
{
return x.Cal_Grade(tempGrade);
}
由参数x传来的对象调用的都将是student::Cal_Grade

fayekiss 2002-04-01
  • 打赏
  • 举报
回复
The grade of gs=80
这句没错,传的是graduate,函数接收时,回调用student的一个复制构造函数(C++编译器自动产生)强制转换成了student.
我不懂电脑 2002-04-01
  • 打赏
  • 举报
回复
结果是对的呀。
The grade of s=80 //student
The grade of gs=86 //graduate
The grade of s=80 //student
The grade of gs=80 //graduate强制转换成了student
prototype 2002-04-01
  • 打赏
  • 举报
回复
Cal_Grade should be virtual. if not, 'x.Cal_grade' will call 'student's member function instead of the 'graduate's.

69,381

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧