qfedu-cpp-level/day8/d8.cpp

51 lines
1002 B
C++

// 异常变量生命周期
// 如 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
{
throw Exception("异常");
}
catch (Exception &e)
{
cout << "捕获异常: " << e.getMsg() << endl;
}
return 0;
}