C++多态性

来源:互联网 发布:高中生能学编程吗 编辑:程序博客网 时间:2024/04/28 00:23
#include <iostream>


using namespace std;


class Student //定义一个学生类;
{
private:
char Name[8];
char Number[11];
char Sex[2];
public:
Student(char Name[8], char Number[11], char Sex[2])
{
strcpy(this ->Name, Name);
strcpy(this ->Number, Number);
strcpy(this ->Sex, Sex);
}


virtual void StuWalk()
{
cout << "student walk" << endl;
}



void output()
{
cout << Name << endl;
cout << Number <<endl;
cout << Sex << endl;
}


};


class NewStudent:public Student  //定义一个新生类,继承学生类
{
public:
NewStudent():Student("xxx", "xxx", "x")
{
//初始化代码
}
void StuWalk()
{
cout << "new student walk" << endl;
}

};


void outPutWalk(Student* STU)  //定义一个全局函数,传递Student类的地址,输入Stuwalk属性
{
STU -> StuWalk();
}


void main()
{
NewStudent Nst;
Nst.output();
Nst.StuWalk();   // 函数覆盖,重载函数时调用子类的函数,若父类是虚函数,
cout << "-----------------------------------" << endl;
NewStudent Nst1;
Student *Stu; 
Stu = &Nst1;
outPutWalk(Stu);   //执行结果表明输出的是父类的函数,若要输出子类的函数,则采用virtual机制,实现多态性,迟绑定技术
 


}
0 0
原创粉丝点击