注册 登录
编程论坛 C++教室

异常处理的问题

lyj23 发布于 2011-05-17 20:18, 258 次点击
程序代码:
#include <cstddef>
#include <iostream>
#include <conio.h>
using namespace std;
template<class T,int sz=1>class PWrap{
T*ptr;
public:
       class Rangeerror{};
       PWrap(){
        ptr=new T[sz];
        cout<<"PWrap constructor"<<endl;}
        ~PWrap()
        {delete[]ptr;
        cout<<"PWrap destructor"<<endl;}
       T& operator [](int i)throw(Rangeerror){
                   if(i>=0&&i<sz)return ptr[i];
        throw Rangeerror();}
        };
class Cat{
public:
       Cat(){cout<<"Cat()"<<endl;}
       ~Cat(){cout<<"~Cat{}"<<endl;}
       void g(){}};
class Dog{
public:
       void* operator new[](size_t){
             cout<<"Allocating a Dog"<<endl; //这个重载在哪里用到了?size_t是无符号长整型吗? (1)
             throw 47;}
       void operator delete[](void* p){
            cout<<"Deallocating a Dog"<<endl;
            ::operator delete[](p);}   //这一句能不能换种写法?它的意思是不是清除p的空间,是不是还原运算符重载?
            };
class UseResources{
      PWrap<Cat,3>cats;
      PWrap<Dog>dog;
      public:
      UseResources(){cout<<"Use()"<<endl;}
      ~UseResources(){cout<<"~Use()"<<endl;}
      void f(){cats[1].g();}};//是这里用了 (1)重载?
int main()
{
try{UseResources ur;}catch(int){
  cout<<"inside handler"<<endl;}catch(...){
                cout<<"inside catch(...)"<<endl;}
                getch();
}
没时间了,请大家帮忙仔细分析一下整个程序吧,书上写的比较少(选自C++编程思想 第二卷)
2 回复
#2
寒风中的细雨2011-05-17 23:11
class UseResources
{
private:
    PWrap<Cat,3>cats;
    PWrap<Dog>dog;
public:
    UseResources(){cout<<"Use()"<<endl;}
    ~UseResources(){cout<<"~Use()"<<endl;}
    void f(){cats[1].g();}
};
这里用到了类的组合  
在类实例化得过程当中 构造的顺序 cats   dog  然后再是自身的构函{ ...... }

运行结果:
只有本站会员才能查看附件,请 登录


中间有一段没有进行构造  因为抛出了异常
    try
    {
        UseResources ur;
    }//对象生命期结束  反序进行析构
    catch(int)
    {
        cout<<"inside handler"<<endl;//捕获异常  输出
    }
#3
lyj232011-05-20 06:06
THINKS
1