首页 > 编程语言 > 详细

c++ 指针类型转换

时间:2019-09-20 17:31:49      阅读:144      评论:0      收藏:0      [点我收藏+]

1、数据类型转换(static_cast)

//数据类型转换
printf("%d\n", static_cast<int>(10.2));

2、指针类型转换(reinterpret_cast)
//指针类型转换
  int *pint = new int(1);
  char *pch = reinterpret_cast<char *>(pint);

3、涉及到const的指针类型转换(const_cast)
  const int num[5] = { 1,2,3,4,5 };
  const int *p = num;
  int *pint = const_cast<int *>(p);

4、子类转化为父类(dynamic_cast)

class man
{
public:
    int name;
    //加上virtual关键字,可以使得父类用子类初始化后可以调用子类的函数
    virtual void run()
    {
        cout << "man is running" << endl;
    }
};

class son :public man
{
public:
    void run()
    {
        cout << "son is running" << endl;
    }
};

void main()
{
    /*man man1;
    son son1;
    man *p = &man1;
    p->run();
    p = &son1;
    p->run();*/
    man *pman = new man;
    son *pson = new son;
    //子类指针转换为父类指针,但是还是调用子类的函数
    man *pfu = dynamic_cast<man *>(pson);
    pfu->run();
    system("pause");
}

 

c++ 指针类型转换

原文:https://www.cnblogs.com/lovebay/p/11558472.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!