C++面向对象编程
基类指针指向派生类对象
因为派生类对象也是基类对象 , 所以指向派生类对象的执政可以转换成指向基类对象的指针, 这种应用是安全的
为了明确完成向上映射转换, C++提供了dynamic_cast 运算符
格式如下:
dynamic_cast<类型》(表达式)
派生类对象作为基类处理对象 所以把派生类的对象赋给基类对象是合理的
eg
class B:public A
{
int y ;
public :
B(int i ,int j) :A(i) {y = j;}
}
下面看实际的类子
程序功能是将大学生和研究生的分数转换为对应的等级并且输出
功能简单
代码:
#include<iostream>
#include<string.h>
using namespace std;
class Student
{
char name[13];
int score ;
public:
//构造函数
Student(char na[], int s)
{
strcpy(name, na);
score = s;
}
void disp()
{
cout<<name<<" "<<score<<" ";
//下面将进行成绩优秀良好的判断
if(score >=90)
{
cout<<"优秀"<<endl;
}
else if(score>=80)
{
cout<<"良好"<<endl;
}
else if(score >= 70)
{
cout<<"中等"<<endl;
}
else if(score >= 60)
{
cout<<"及格"<<endl;
}
else
{
cout<<"不及格"<<endl;
}
}
};
class Unstud:public Student
{
char cname[13];
public:
Unstud(char na[], char cn[], int s):Student(na, s)
{
//派生类作为处理对象处理
strcpy(cname, cn);
}
};
class GrandStud:public Student
{
char research[13];
public:
GrandStud(char na[], char rs[], int s):Student(na, s)
{
strcpy(research, rs);
}
};
int main()
{
Student *p;
Unstud a("李明","计算机科学",85);
GrandStud b("王华", "数据挖掘",94);
p = dynamic_cast<Student*>(&a);
p->disp();
p =dynamic_cast<Student*>(&b);
p->disp();
return 0;
}