第18讲
教学内容
类型兼容规则
教学重点和难点
1类型兼容规则的理解
教学方法:
通过程序举例演示,讲解类型兼容规则
教学学时
2 学时
教学过程
一类型兼容规则的理解:
一个公有派生类的对象在使用上可以被当作基类的对象,反之则禁止。具体表现在:
–派生类的对象可以被赋值给基类对象。
–派生类的对象可以初始化基类的引用。
–指向基类的指针也可以指向派生类。
通过基类对象名、指针只能使用从基类继承的成员
程序举例1:分析下列程序的输出结果:
class People
{
private:
char m_name[20];
protected:
char m_address[40];
public:
void SetPeopleData(char name[20],char address[40]);
char * GetName();
char *GetAddress();
void ShowInfo();
};
void People::SetPeopleData(char name[20],char address[40])
{
strcpy(m_name,name);
strcpy(m_address ,address);
}
char * People::GetName() { return m_name;}
char * People::GetAddress() { return m_address;}
void People::ShowInfo()
{
cout << "姓名:"<<m_name << endl;
cout << "家庭地址:"<<m_address << endl;
}
class Student:public People
{
private:
int m_ID;
public:
void SetStudentData(char name[20],char address[40],int ID);
int GetID();
void ShowInfo();
};
void Student::SetStudentData(char name[20],char address[40],int ID)
{
SetPeopleData(name,address);
m_ID = ID;
}
int Student::GetID() { return m_ID;}
void Student::ShowInfo()
{
People::ShowInfo();
cout <<"学号:"<<m_ID << endl;
}
void main(void)
{
Student s;
("小张","武汉",20060201);
//一个公有派生类的对象在使用上可以被当作基类的对象,反之则禁止。具体表现在:
//任何适用于基类的地方都适合派生类
//1)派生
第18讲(类型兼容规则) 来自淘豆网www.taodocs.com转载请标明出处.