#include <iostream>
#include <string>
#include <new>
using std::cout;
using std::endl;
using std::string;
using std::bad_alloc;
int sum(int a,int b);
int product(int a,int b);
int result(int a,int b,int (*pResult)(int,int));
int main(void)
{
for(int i = 0;i < 2;++i)
try{
int (*pdo_it)(int,int); ///< 定义函数指针
pdo_it = product;
int result1 = pdo_it(3,5);
cout<<endl
<<"3*5 = "<<result1;
pdo_it = sum;
int result2 = pdo_it(product(3,pdo_it(4,5)),6);
cout<<endl
<<"3*(4+5)+6 = "
<<result2;
cout<<endl;
cout<<"The sum result is: "
<<result(result1,result2,sum);
cout<<endl;
if (0 == i){///< test
throw string("Zero");
}
}catch (const string eroMsg){
cout<<eroMsg
<<endl;
}
///<一个new失败抛出异常的例子
char* pdata = NULL;
size_t count = ~static_cast<size_t>(0)/2;
try{
pdata = new char[count]; ///< new failed throw exception.
cout<<"Memory allocated."<<endl;
}catch(bad_alloc &ex){ ///< new failed return this type (include in file new).
cout<<"Memory allocated failed."<<endl
<<"The information from the exception object is: "
<<ex.what()<<endl;
}
delete [] pdata;
system("pause");
return 0;
}
int sum( int a,int b )
{
return a+b;
}
int product( int a,int b )
{
return a*b;
}
int result( int a,int b,int (*pResult)(int,int) )
{
return pResult(a,b);
}