|
跟着第41课敲代码的时候。视频上面说可以强制转换因为基类是XiaoStudent。
但我的63行编译的时候总是提示我无法进行该项转换。这是为啥啊?
#include<iostream>
#include<string>
using namespace std;
enum EStudentType
{
EStudentType_erro = 0,
EStudentType_xiao ,
EStudentType_zhong
};
class Student
{
public:
char* pname;
char sex;
int age;
int num;
Student() {};
//~Student() {};
EStudentType type;
};
class XiaoStudent :public Student
{
public:
int yuwen;
int shuxue;
int yingyu;
XiaoStudent()
{
type = EStudentType_xiao;
//shuxue = 50;
}
};
class Zhongxue :public XiaoStudent
{
public:
int wuli;
int huaxue;
Zhongxue()
{
type = EStudentType_zhong;
}
};
int average_age(Student* p_arr_stud, int n_size)
{
if (!p_arr_stud || n_size == 0)
return 0;
int age_sum = 0;
EStudentType stud_type = p_arr_stud[0].type;
for (int idx = 0; idx < n_size; ++idx)
{
switch (stud_type)
{
case EStudentType_xiao:
age_sum += ((XiaoStudent*)p_arr_stud)[idx].age;
break;
case EStudentType_zhong:
age_sum += ((Zhongxue*)p_arr_stud[idx]).age;
break;
default:
break;
}
}
int ave_age = age_sum / n_size;
switch (stud_type)
{
case EStudentType_xiao:
cout << "当前小学生的平均年龄是:" <<ave_age<< endl;
break;
case EStudentType_zhong:
cout << "当前中学生的平均年龄是:" << endl;
break;
}
return ave_age;
}
int main()
{
XiaoStudent stud[3];
stud[0].age = 20;
stud[1].age = 20;
stud[2].age = 60;
average_age(stud, 3);
return 0;
}
把63行代码改为:
- age_sum += ((Zhongxue*)p_arr_stud)[idx].age;
复制代码
|
上一篇: mfc怎么改变ICheckEditor的字体颜色下一篇: 为什么函数中形参是char *型
|