栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

解析C++编程中的bad_cast异常

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解析C++编程中的bad_cast异常

由于强制转换为引用类型失败,dynamic_cast 运算符引发 bad_cast 异常。
语法

catch (bad_cast)
  statement

备注
bad_cast 的接口为:

class bad_cast : public exception {
public:
  bad_cast(const char * _Message = "bad cast");
  bad_cast(const bad_cast &);
  virtual ~bad_cast();
};

以下代码包含失败的 dynamic_cast 引发 bad_cast 异常的示例。

// expre_bad_cast_Exception.cpp
// compile with: /EHsc /GR
#include 
#include 

class Shape {
public:
  virtual void virtualfunc() const {}
};

class Circle: public Shape {
public:
  virtual void virtualfunc() const {}
};

using namespace std;
int main() {
  Shape shape_instance;
  Shape& ref_shape = shape_instance;
  try {
   Circle& ref_circle = dynamic_cast(ref_shape); 
  }
  catch (bad_cast b) {
   cout << "Caught: " << b.what();
  }
}

由于强制转换的对象 (Shape) 不是派生自指定的强制转换类型 (Circle),因此引发异常。若要避免此异常,请将下列声明添加到 main:

Circle circle_instance;
Circle& ref_circle = circle_instance;

然后在 try 块中反转强制转换的意义,如下所示:

Shape& ref_shape = dynamic_cast(ref_circle);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/64633.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号