#include<iostream>
using namespace std;
class Animal
{
public:
virtual void action()
{
cout<<"the action is animal's "<<endl;
}
};
class Dog:public Animal
{
public:
virtual void action()
{
cout<<"the action is dog's "<<endl;
}
void doSwim()
{
cout<<"the dog is swimming..."<<endl;
}
};
class Cat:public Animal
{
public:
virtual void action()
{
cout<<"the action is cat's "<<endl;
}
void doTree()
{
cout<<"the cat is claming tree..."<<endl;
}
};
class Desk
{
public:
void action()
{
cout<<"this is Desk, not belong Animal"<<endl;
}
};
void ObjPlay(Animal *animl)
{
animl->action();
Dog *dog = dynamic_cast<Dog *>(animl);
if(dog!=NULL) //判断是不是dog
{
dog->action();
dog->doSwim();
}
Cat *cat = dynamic_cast<Cat *>(animl);
if(cat!=NULL) //判断是不是cat
{
cat->action();
cat->doTree();
}
cout<<"func ObjPlay is exit!!!\n"<<endl;
}
//典型用法 把形参的只读属性去掉
void Opbuf(const char *p)
{
cout << p << endl;
//char *p2 = p; err:const char *不能初始化为char *
//p[0] = 'b'; err:必须是可修改的左值
char *p2 = const_cast<char*>(p); //去除只读的属相
p2[0] = 'b';
cout << p << endl;
}
int main()
{
//静态类型转化 static_cast<>()
double d = 3.14159;
int i1,i2;
i1 = d; //C中的隐式类型转化
i2 = static_cast<int>(d); //C++中的静态类型转化
cout<<"C中类型转化:"<<i1<<endl;
cout<<"C++中类型转化:"<<i2<<endl;
//重新解释类型reinterpret_cast<>()
char *p = "abcd";
int *p1 = NULL;
int *p2 = NULL;
p1 = (int *)p; //C中强制类型转化
//p2 = static_cast<int *>(p); 编译报错,类型转化错误,静态类型不能转化指针
p2 = reinterpret_cast<int *>(p); //C++中的重新解释类型
cout<<"C中类型转化"<<hex<<*p1<<endl;
cout<<"C++中类型转化:"<<hex<<*p2<<endl;
//动态类型转换 dynamic_cast<>()
Animal an;
Animal *pAn = &an;
ObjPlay(pAn);
Dog dog;
Dog *pDog = &dog;
ObjPlay(pDog);
Cat cat;
Cat *pCat = &cat;
ObjPlay(pCat);
Desk desk;
Desk *pDesk = &desk;
//Animal *pAn = dynamic_cast<Animal*>(pDesk); 不同的基类指针之间不能相互转化,安全
//去除变量的只读属性,const_cast<>(),此类型必须是指针
char buf[100] = "aaaaaaaaaaaa";
//Opbuf(buf);
//要保证指针所执行的内存空间能修改才行 若不能修改 还是会引起程序异常
//Opbuf("dddddddddddsssssssssssssss");
system("pause");
return 0;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有