父类对象与子类对象之间的相互转换
3、小作业,刚刚的 average_age 函数我改成这样行不行?
void average_age(CStudent* p_arr_stud, int n_size) { int total_age = 0; if (!p_arr_stud || n_size <= 0) return; for (int idx = 0; idx < n_size; ++idx) { total_age += p_arr_stud[idx].age; } EStudentType type = p_arr_stud[0].type; int aver_age = total_age / n_size; switch (type) { case EStudentType_Xiao: cout << "小学生的平均年龄是:" << aver_age << endl; break; case EStudentType_Zhong: cout << "中学生的平均年龄是:" << aver_age << endl; break; default: break; } }
代码看着很简洁,不知道结果是否正确,大家不妨先试试,如果结果正确那没什么说的,如果结果不争取,那是为什么呢?为什么会出现这样的情况?还请大家课后仔细想想!
#include <iostream> using namespace std; enum EStudent { Student = 0, EStudentType_Xiao, EStudentType_Zhong }; class CStudent { public: int age; EStudent type = Student; }; class CStudent_xiao:public CStudent { public: int a = 0; CStudent_xiao() { type = EStudentType_Xiao; } }; class CStudent_zhong :public CStudent_xiao { public: int a = 0; int b = 0; int c = 0; CStudent_zhong() { type = EStudentType_Zhong; } }; void average_age(CStudent* p_arr_stud, int n_size) { int total_age = 0; if (!p_arr_stud || n_size <= 0) return; for (int idx = 0; idx < n_size; ++idx) { total_age += p_arr_stud[idx].age; } EStudent type = p_arr_stud[0].type; int aver_age = total_age / n_size; switch (type) { case EStudentType_Xiao: cout << "小学生的平均年龄是:" << aver_age << endl; break; case EStudentType_Zhong: cout << "中学生的平均年龄是:" << aver_age << endl; break; default: break; } } int main() { CStudent_zhong a[4]; a[0].age = 10; a[1].age = 25; a[2].age = 40; a[3].age = 50; average_age(a, 4); return 0; }
| 指针没有经过强制转换的话,结果是错误的,因为第一个参数传进来的是数组基类指针,数组首地址都是相同的,但是数组的第二个元素开始是首地址+对象大小,所以不经过转换的话是得不到子类对象的正确地址的。 |
浙公网安备 33010602011771号