看看这段异常代码,在线等?

10water 2003-04-13 07:52:10
//a.h 中
#include <iostream>
using namespace std;
class animal
{
public:
animal();
animal(int _age);
void cry();
void virtual run();
private:
int _name;
int _age;
};
animal::animal()
{
cout<<"this is a anmiam"<<endl;
}
animal::animal(int _age)
{
cout<<"the animal age is "<<_age<<endl;
if(_age>60)
throw animal(_age);
}
void animal::cry()
{
cout<<"zhe animal is cry"<<endl;
}
void animal::run()
{
cout<<"the animal is run()"<<endl;
}


class dog : public animal
{
public:
dog();

void cry();
void virtual run();
private:
int zl;
};
dog::dog()
{
cout<<"this is a dog!"<<endl;
}

void dog::cry()
{
cout<<"zhe dog is cry"<<endl;
}
void dog::run()
{
cout<<"zhe dong is run"<<endl;
}


// a.cpp 中
#include <iostream>
#include <string>
#include "a.h"
using namespace std;
void main()
{
try
{
animal an(90);
}
catch(const animal & a)
{
cout<<"animal is ex"<<endl;
}
catch(const dog & d)
{
cout<<"dog is ex"<<endl;
}

}

为什么 运行后 是个死循环?
...全文
73 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
98440622 2003-04-14
  • 打赏
  • 举报
回复
It's beyong my control, sorry!
up!
ghtsao 2003-04-13
  • 打赏
  • 举报
回复
单独创建异常对象,不要自己处理自己抛出的异常。
ghtsao 2003-04-13
  • 打赏
  • 举报
回复
是递归死循环了。
vosbtis 2003-04-13
  • 打赏
  • 举报
回复
在 执行 throw animal(_age); 中,系统的处理的步骤为:
1. 先执行 animal tmp(_age);
2. 然后在进入 catch(const animal & a)前
执行 a = tmp;

由于 animal tmp(_age) 进入了无终止的递归,
所以未执行 2.
10water 2003-04-13
  • 打赏
  • 举报
回复
那在catch(const animal & a)
处的警告事怎么形成的?
theninthsky 2003-04-13
  • 打赏
  • 举报
回复
用其他方法标示错误,不要用抛出异常
langzi8818 2003-04-13
  • 打赏
  • 举报
回复
:)
fiveyes 2003-04-13
  • 打赏
  • 举报
回复
建议创建一个别的什么对象,专门用来表示错误,到时候抛它,不要抛anamal了。
fiveyes 2003-04-13
  • 打赏
  • 举报
回复
同意楼上。这死循环是这样形成的:

在构造函数中,先打印一行字,然后由于_age大于60,于是抛出异常,在抛出异常的时候,又要创建一个对象,于是又要调用构造函数,又打印一行字,又发现_age大于60,于是又抛出异常,在抛出异常的时候,又要创建一个对象,于是又得调用构造函数……
skywebnet 2003-04-13
  • 打赏
  • 举报
回复
……
animal::animal(int _age)
{
cout<<"the animal age is "<<_age<<endl;
if(_age>60)
throw animal(_age); //递归问题
}
……
void dog::run()
{
cout<<"zhe dong is run"<<endl; //虚函数问题
}



10water 2003-04-13
  • 打赏
  • 举报
回复
另外 还有两个警告是怎么回事?

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧