传智扫地僧课程学习笔记。
#include "iostream"
using namespace std;
class tree
{
};
class animal
{
public:
virtual void cry() = 0;
};
class dog : public animal
{
public:
virtual void cry()
{
cout<<"wang wang"<<endl;
}
void dohome()
{
cout<<"watch home"<<endl;
}
};
class cat : public animal
{
public:
virtual void cry()
{
cout<<"miao miao"<<endl;
}
void dothing()
{
cout<<"cat mouse"<<endl;
}
};
void objplay( animal *base)
{
base->cry();
dog *pdog = dynamic_cast<dog *>(base);
//dynamic_cast 运行时候类型识别,从而执行各自特有的工作,否则只能执行共有的方法,
if( pdog != NULL )
{
pdog->dohome();
}
cat *pcat = dynamic_cast<cat *>(base);
if( pcat != NULL )
{
pcat->dothing();
}
//父类对象转向子类对象,向下转型,
}
void main()
{
dog d1;
cat c1;
animal *pbase = NULL;
pbase = &d1;
pbase = static_cast<animal *>(&d1);
pbase = reinterpret_cast<animal *>(&d1);
tree t1;
pbase = static_cast<animal *>(&t1);//会做类型检查,会报错
pbase = reinterpret_cast<animal *>(&t1);//重新解释,强制类型转换的味道,至于能不能用,就不管了
objplay( &d1);
objplay( &c1);
cout<<"hello"<<endl;
system("pause");
}
//reinterpret_cast不能转换基础数据类型
//