首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

catch基类擒获了throw但是what()没反应

2014-01-09 
catch基类捕获了throw但是what()没反应#includeiostream#includeexceptionusing std::coutclass bad_

catch基类捕获了throw但是what()没反应

#include<iostream>
#include<exception>
using std::cout;
class bad_hmean :public std::logic_error
{
private:
double a;
double b;
public:
bad_hmean(double x, double y, const std::string&s = " ") :a(x), b(y), logic_error(s){}
virtual void what();

};
void bad_hmean::what()
{
if (a == -b)
     cout<<a<<" and "<<b<<" in the hmean() is bad";
else if (a<0||b<0)
cout << a << " and " << b << " in the gmean() is bad";
}
上面是头文件
#include"标头.h"
#include<cmath>
using std::cout;
using std::cin;
using std::endl;
double hmean(double a, double b);
double gmean(double a, double b);
int main()
{
double x, y, z;
cout << "Enter two numbers: ";
while (cin >> x >> y)
{
try
{
z = hmean(x, y);
cout << "hmean of " << x << " and " << y << " is " << z << endl;
cout << "gmean of " << x << " and " << y << " is " << gmean(x, y) << endl;
cout << "Enter next set of numbers: ";
}
catch (std::logic_error&bad)
{
bad.what();//问题就是这里,明明捕获了,为毛不显示what里面
break;     //的内容呢?bad.what()不是优先显示派生类的what()
}                 //内容吗?
}
cout << "Bye\n";
return 0;
}
double hmean(double a, double b)
{
if (a == -b)
throw bad_hmean(a,b);
return 2.0*a*b / (a + b);
}
double gmean(double a, double b)
{
if (a < 0 || b < 0)
throw bad_hmean(a,b);
return std::sqrt(a*b);
}
谢谢大神们!
[解决办法]
virtual const char* what() const throw();
这才是what的函数原型

热点排行