Evo. G Tech Team Forum
Welcome to Evo. G Tech Team Forum. We have moved to a new website : www.evogtechteam.com

Thanks you.

by Evo. G Tech Team Management.

Join the forum, it's quick and easy

Evo. G Tech Team Forum
Welcome to Evo. G Tech Team Forum. We have moved to a new website : www.evogtechteam.com

Thanks you.

by Evo. G Tech Team Management.
Evo. G Tech Team Forum
Would you like to react to this message? Create an account in a few clicks or log in to continue.

四种强制类型转换之一dynamic_cast

Go down

四种强制类型转换之一dynamic_cast Empty 四种强制类型转换之一dynamic_cast

Post by too wei June 28th 2015, 19:08

dynamic_cast
-用来将一个父类指针转换成子类指针,称为安全向下转型safe downcasting
-被用于多态类情况下的方向操作
-dynamic_cast 会检查转换是否合法,也就是说它会检查类型转换操作是否会返回一个被要求类型的有效的完整的对象,如果不能,返回null指针(如果是static_cast,会返回一个不正确的指针 ),这  个检查会在运行时执行
-消耗大,尽量不要用


Code:

class father { virtual void show() {}};           //因为dynamic_cast只能用于有多态性的类
class son:public father{virtual void show() {}};

int main()
{
   son *f = new son;

   try
   {
      father *s = dynamic_cast(f);
      if(s == NULL)        //如果父类转换去子类,这里就会为true,因为转换不安全,dynamic_cast返回null指针
      {
         printf("NULL pointer,fail to convert\n");
      }
   }
   catch (bad_cast &)
   {
      printf("Caught bad_cast\n");
   }
   return 0;
}


如果用在引用(reference)类型上,而这个转换不可能进行的话(父类到子类),bad_cast异常将会被抛出

class father { virtual void show() {}};           //因为dynamic_cast只能用于有多态性的类
class son:public father{virtual void show() {}};

Code:
int main()
{
   father f;
   father &f2 = f; //引用

   try
   {
      son f = dynamic_cast(f2); //引发 bad_cast异常
   }
   catch (bad_cast)              //捕捉bad_cast
   {
      printf("Caught bad_cast!\n");   //其实你应该好好处理异常,而不是像我只打印一点信息
   }
   return 0;
}

too wei
Sponsor
Sponsor

Posts : 31
Points : 66331
Reputation : 0
Join date : 2015-04-21
Age : 25
Location : Johor

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum