您的位置:首页 > 编程语言 > C语言/C++

C++--四种类型转化杂记,学习代码

2017-03-06 21:06 309 查看
/*

粗浅的使用:

static_cast//类似于C,验证性的类型转换

reinterpret_cast//强制性的,重新定义,但是不管你改成什么

const_cast//取消了const属性,但是注意你修改的变量要求可读,这里设计指针变量和数组变量存储字符串的细微区别,看我前一篇文章

dynamic_cast//可以用来转化类

*/

#include <iostream>

using namespace std;

class Animal

{

public:
virtual void cry()=0;

};

class Dog:public Animal

{

public:
virtual void cry()
{
std::cout<<"wang wang "<<std::endl;
}

void dohome()
{
std::cout<<"kan jia"<<std::endl;
}

};

class Cat:public Animal

{

public:
virtual void cry()
{
std::cout<<"miao miao "<<std::endl;
}

void dothing()
{
std::cout<<"zhuao lao shi"<<std::endl;
}

};

void play(Animal *base)//有一个辨别是哪一个子类对象的需求,区分猫和狗,用dynamic_cast来实现

{
base->cry();
Dog *pDog=dynamic_cast<Dog *>(base);
if(pDog !=NULL)
{
pDog->dohome();
}

Cat *pCat=dynamic_cast<Cat *>(base);
if(pCat !=NULL)
{
pCat->dothing();
}

}

void main()//本程序vc++6.0貌似不支持,但是别的编译器支持,只要是不支持该种类型转换,希望大家求证

{
Dog d1;
Cat c1;
play(&d1);
play(&c1);

}

/************************************************************************************************************************/

/*

void printfBuf(const char *p)

{

// p[0]='z';
char *p1=NULL;
p1=const_cast<char *>(p);
p1[0]='z';
std::cout<<p<<std::endl;

}

void main(int argc,char *argv[])

{
double dpi=3.14159;
int num1=(int) dpi;//C语言类型转换
int num2=static_cast<int>(dpi);//静态类型转换 编译时C++编译器会对类型检查
int num3=dpi;//C语言隐式类型转换的地方,均可以使用static_cast<>()来进行转换

std::cout<<num1<<'\n'<<num2<<'\n'<<num3<<std::endl;

char *str="hello...";
int *p2=NULL;
p2= reinterpret_cast<int *>(str);//不同类型之间进行强制转换,用reinterpret_cast<>()转换,进行重新解释
std::cout<<str<<'\n'<<std::endl;
std::cout<<p2<<'\n'<<std::endl;
std::cout<<p2+1<<std::endl;

char buf[]="aaaaaaaaaaaaaaaa";
printfBuf(buf);

}

  */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: