|
// 异常处理.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <exception>
#include <string>
using namespace std;
class CustomException : public exception
{
private:
string reason;
public:
CustomException(string reason)
{
this->reason = reason;
}
~CustomException()
{
cout << "调用CustomException的析构函数" << endl;
}
const char* what() const throw()
{
return reason.c_str();
}
};
double Division(double divisor,double dividend)
{
if (dividend == 0)
{
throw CustomException("除数为零");
}
return divisor / dividend;
}
int main()
{
try
{
cout << "结果为" << Division(8, 0) << endl;
}
catch (exception& exp)
{
cout << exp.what() << endl;
}
}
问题:
exception异常处理类的派生类CustomException 类的声明,其中what()函数为子类与父类的同名函数
class CustomException : public exception
{
private:
string reason;
public:
CustomException(string reason)
{
this->reason = reason;
}
~CustomException()
{
cout << "调用CustomException的析构函数" << endl;
}
const char* what() const throw()
{
return reason.c_str();
}
};
普通函数Division声明,形参为exception给异常处理类对象
double Division(double divisor,double dividend)
{
if (dividend == 0)
{
throw CustomException("除数为零");
}
return divisor / dividend;
}
try-catch结构,其中catch捕获的是exception对象,但是我的Division函数抛出的是CustomException类型的对象
try
{
cout << "结果为" << Division(8, 0) << endl;
}
catch (exception& exp)
{
cout << exp.what() << endl; // 最终调用的是CustomException中的what()函数
}
我想问的是:当CustomException子类的对象按照值传递的方式传递给exception父类对象,按道理来讲应该发生了“割去问题”,调用的应该是exception对象的what()函数,那为什么最终的结果是调用了CustomException子类的what()函数呢?
|
上一篇: 论坛的源码能用Visual Studio运行吗下一篇: Spin控件能不能设置步进值
|