![]() |
#2
寒风中的细雨2011-05-17 23:11
|

#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++编程思想 第二卷) #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();
}