qfedu-cpp-level/day8/d7.cpp

53 lines
1.1 KiB
C++

// 异常变量生命周期
// 如 1: 抛出对象,接收对象,会使用拷贝构造函数
// 异常变量生命周期
// 如 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;
}