//多态 polymorphism
#include<iostream>
using namespace std;
#include<string>
class Person{
protected:
string name;
private:
bool gender;
public:
void eat(const char* food){cout<<name<<"在吃"<<food<<"."<<endl;}
void sleep();
//虚函数 调用时不会根据指针什么类型调用 而是根据函数什么类型调用
virtual void show(){cout<<"大家好,我是"<<(gender?"男的":"女的")<<name<<endl;}
Person(const char* name,bool gender):name(name),gender(gender){}
string Name()const{return name;}
};
class Teacher:public Person
{
string course;
public:
void teach(const char* _class){
cout<<name<<"在给"<<_class<<"班讲"<<course<<"课程"<<endl;
}
Teacher(const char* name,bool gender,const char* course):Person(name,gender),course(course){ }
void show(const char* _class)//改写来自父类的成员,隐藏来自父类那个同名成员
{cout<<"同学好"<<course<<"老师在这"<<_class<<endl;}
void show()
{cout<<"同学好"<<course<<"老师在这"<<endl;}
};
int main()
{
Person a("hehe",false);
Teacher b("heihei",true,"UNIX C");
Person* p = NULL,*q = NULL;
p = &a;
q = &b;
Person c = b;
Person& d = b;
c.show();
p->show();
q->show();
d.show();
//dynamic_cast<子类*>(父类对象地址) 如果是父类对象的子类 则返回父类地址 否则返回NULL (父类中必须有虚函数)
cout<<dynamic_cast<Teacher*>(q)<<endl;
cout<<dynamic_cast<Teacher*>(p)<<endl;
cout<<dynamic_cast<Teacher*>(&c)<<endl;
cout<<dynamic_cast<Teacher*>(&d)<<endl;
//type_info:类型信息 <typeinfo>
typeid(类型);
typeid(对象);
}
#include<iostream>
using namespace std;
#include<string>
class Person{
protected:
string name;
private:
bool gender;
public:
void eat(const char* food){cout<<name<<"在吃"<<food<<"."<<endl;}
void sleep();
//虚函数 调用时不会根据指针什么类型调用 而是根据函数什么类型调用
virtual void show(){cout<<"大家好,我是"<<(gender?"男的":"女的")<<name<<endl;}
Person(const char* name,bool gender):name(name),gender(gender){}
string Name()const{return name;}
};
class Teacher:public Person
{
string course;
public:
void teach(const char* _class){
cout<<name<<"在给"<<_class<<"班讲"<<course<<"课程"<<endl;
}
Teacher(const char* name,bool gender,const char* course):Person(name,gender),course(course){ }
void show(const char* _class)//改写来自父类的成员,隐藏来自父类那个同名成员
{cout<<"同学好"<<course<<"老师在这"<<_class<<endl;}
void show()
{cout<<"同学好"<<course<<"老师在这"<<endl;}
};
int main()
{
Person a("hehe",false);
Teacher b("heihei",true,"UNIX C");
Person* p = NULL,*q = NULL;
p = &a;
q = &b;
Person c = b;
Person& d = b;
c.show();
p->show();
q->show();
d.show();
//dynamic_cast<子类*>(父类对象地址) 如果是父类对象的子类 则返回父类地址 否则返回NULL (父类中必须有虚函数)
cout<<dynamic_cast<Teacher*>(q)<<endl;
cout<<dynamic_cast<Teacher*>(p)<<endl;
cout<<dynamic_cast<Teacher*>(&c)<<endl;
cout<<dynamic_cast<Teacher*>(&d)<<endl;
//type_info:类型信息 <typeinfo>
typeid(类型);
typeid(对象);
}