qfedu-cpp-level/day8/d9.cpp

53 lines
1.2 KiB
C++
Raw Normal View History

2023-08-02 19:23:29 +08:00
// 异常变量生命周期
// 如 1: 抛出对象(堆区),捕获对象(堆区),会使用拷贝构造函数,需要手动释放内存
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Exception
{
private:
string msg;
public:
Exception()
{
this->msg = "";
cout << this << "Exception()" << endl;
}
Exception(const string &msg)
{
this->msg = msg;
cout << this << "Exception(const string &)" << endl;
}
Exception(const Exception &other)
{
this->msg = other.msg;
cout << this << "Exception(const Exception &)" << endl;
}
~Exception() { cout << this << "~Exception()" << endl; }
public:
string &getMsg() // const 表示该成员函数不会修改成员变量
{
return this->msg;
}
};
int main()
{
try
{
// 要使用 new 创建对象,否则会在栈区创建对象,导致异常抛出时,会调用析构函数
throw new Exception("异常"); // 在堆区创建对象
}
catch (Exception *e)
{
cout << "捕获异常: " << e->getMsg() << endl;
delete e; // 手动释放内存
}
return 0;
}