C++——7(异常&转换函数)
一、异常
1.
异常概念:
C++中一种容错的机制(错误处理方法)
2.
异常的基本思想:
让一个函数在发现了自己无法处理的错误时,抛出一个异常通知他的直接或者间接使用者处理这个问题
3.
异常优点:
保证软件系统运行的稳定性与健壮性
4.
异常处理机制组成:
try
(检查错误)throw
(抛出错误)catch
(捕获异常)#include <stdexception> //C++标准异常头文件 try { if() //错误检查 throw //抛出异常1 if() //检查2 throw //异常2 } catch() //捕获所有异常 { }
二、自定义异常使用
/*=============================================== * 文件名称:5_MyException.cpp * 创 建 者:青木莲华 * 创建日期:2025年09月03日 * 描 述:自定义异常类 ================================================*/ #include <iostream> using namespace std; #include <stdexcept> //自定义异常派生类 class MyException : public exception { public: MyException(const char *err)noexcept : errmsg(err){} const char *what() const noexcept { return errmsg; } private: const char *errmsg; }; float func(int x , int y) { if(y == 0) throw MyException("y is zero"); else if(x == -1) throw MyException("x is -1"); return x / y; } int main(int argc, char *argv[]) { int x,y; INPUT: cin >> x >> y; try { cout << func(x,y) << endl; } catch(const exception &e) { cout << "Error_msg : " << e.what() << endl; goto INPUT; } return 0; }
三、类内转换函数
1.
为什么要转换函数:
将用户自定义类型的数据转换为另一个类型的数据
2.
转换函数的视线:
运算符的重载,只是重载的是用户自定义的函数(不是运算符)
3.
语法规则:
operator 数据类型() { 转换算法; } //1.自定义的转换函数必须是类的成员函数 //2.没有数据类型,空参数,但是可以return //3.不能定义到数组、函数或void的转换 //4.转换函数常用const修饰
- 4.
explicit
作用:
关键字修饰 构造函数,可以防止将一个成员类型 隐式转换为当前类的类型/*=============================================== * 文件名称:8_explicit.cpp * 创 建 者:青木莲华 * 创建日期:2025年09月03日 * 描 述: ================================================*/ #include <iostream> using namespace std; class Demo { public: explicit Demo(int x): x(x){ cout << "constructor called" << endl; } private: int x; }; int main(int argc, char *argv[]) { Demo d1(11); //Demo d2 = 12; 当构造加上 explicit后 无法初始化 //正确写法 Demo obj1 = Demo(12); //explicit 作用:关键字修饰 构造函数,可以防止将一个成员类型 隐式转换为当前类的类型 return 0; }
四、标准转换函数
函数分类:
编译时转换:
- reinterpret_cast(将一个类型的
指针
转换为另一个类型的指针)- static_cast(主要用于继承类之间的转换)
- const_cast(主要用于将
const
修饰的变量转换为非const
的变量)运行时转换:
- dynamic_cast(只有
类中含有虚函数
才能用该方法转换,仅能在继承类对象之间转换,比static_cast更安全)
reinterpret_cast用例:
int main(int argc, char *argv[]) { char *p1 = NULL; int *p2 = NULL; p2 = reinterpret_cast<int *>(p1); }
const_cast用例:
const char *p1 = "Hill"; char *p2 = NULL; p2 = const_cast<char *>(p1);
static_cast用例:
dynamic_cast用例: