设为首页 加入收藏

TOP

C++类型转换代码教程
2018-04-08 08:51:12 】 浏览:181
Tags:类型 转换 代码 教程

C++类型转换代码教程

#define _CRT_SECURE_NO_WARNINGS
#include 
  
   
using namespace std;


class Building{};
class Animal {};
class Cat: public Animal{};

//static_cast
void test01()
{
	int a = 99;
	char c = static_cast
   
    (a); cout << c << endl; //基础数据类型指针 //int* p = NULL; //char* sp = static_cast
    
     (p); //对象指针 //Building* building = NULL; //Animal* ani = static_cast
     
      (building); //转换具有继承关系的对象指针 //父类指针转成子类指针 Animal* ani = NULL; Cat* cat = static_cast
      
       (ani); //子类指针转成父类指针 Cat* soncat = NULL; Animal* anifather = static_cast
       
        (soncat); #if 0 Animal aniobj; Animal& aniref = aniobj; Cat& cat = static_cast
        
         (aniobj); #endif Cat catobj; Cat& catref = catobj; Animal& anifather2 = static_cast
         
          (catref); //static_cast 用于内置的数据类型 //还有具有继承关系的指针或者引用 } //dynamic_cast 转换具有继承关系的指针或者引用,在转换前会进行对象类型检查 void test02() { //基础数据类型 //int a = 10; //char c = dynamic_cast
          
           (a); //非继承关系的指针 //Animal* ani = NULL; //Building* building = dynamic_cast
           
            (ani); //具有继承关系指针 //Animal* ani = NULL; //Cat* cat = dynamic_cast
            
             (ani); //原因在于 dynamic做类型安全检查 Cat* cat = NULL; Animal* ani = dynamic_cast
             
              (cat); //结论 :dynamic只能转换具有继承关系的指针或引用 //并且只能由子类型转换成基类型 } //const_cast 指针 引用 或者 对象指针 void test03() { //基础数据类型 int a = 10; const int& b = a; //b = 10; int& c = const_cast
              
               (b); c = 20; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; //指针 const int* p = NULL; int* p2 = const_cast
               
                (p); int* p3 = NULL; const int* p4 = const_cast
                
                 (p3); //增加或者去除变量的const性 } //reinterpret_cast 强制类型转换,无关的指针,包括函数指针都可以进行转换 typedef void(*FUNC1)(int, int); typedef int(*FUNC2)(int, char*); void test04() { //1. 无关的指针类型都可以进行转换 Building* building = NULL; Animal* ani = reinterpret_cast
                 
                  (building); //2. 函数指针转换 FUNC1 func1; FUNC2 func2 = reinterpret_cast
                  
                   (func1); } int main() { //test01(); //test02(); //test03(); test04(); return 0; } /* 结论1:程序员必须清楚的知道要转变的变量,转换前是什么类型,以及转换后有什么后果 结论2:一般情况下,不建议类型转换,避免进行类型转换 */
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C/C++中的相对路径和绝对路径以及.. 下一篇数据库知识学习之C C++ 操作系统..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目