|
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
void ShowInf()
{
cout << "使用Person对象" << endl;
}
};
class Student:public Person
{
public:
void ShowInf()
{
cout << "调用Student对象" << endl;
}
};
void Practice(Person& person)
{
person.ShowInf();
}
int main()
{
Person person;
Practice(person);
}
在这个程序中,Practice函数参数为Person父类的引用,当我传递给Practice函数Student子类的对象时,由于是值传递因此person.ShowInf()调用的是person的ShowInf().那为什么如下的程序会不同呢?
#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;
}
virtual const char* what() const noexcept // throw()与noexcept等价,表明:在这个函数作用域内不可以抛出任何异常
{
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;
}
}
同样,catch捕捉的是exception的形参,但是我throw的确是exception子类CustomException的形参,如果按照值传递exp.what()调用的应该是exception自己的what()函数才是呀?为什么调用exception子类CustomException的what()函数? |
上一篇: 高手帮忙看看 CoCreateInstance 返回 E_NOINTERFACE下一篇: 异常处理问题
|