数据结构算法与应用c++语言描述 原书第二版 答案(更新中

目录

第一章 C++回顾

函数与参数

1.交换两个整数的不正确代码。

异常

10.抛出并捕捉整型异常。


第一章 C++回顾

函数与参数

1.交换两个整数的不正确代码。

//test_1
void swap(int x,int y)
{
	int temp=x;
	x=y;
	y=temp;
}
void swap2(int& x,int& y)
{
	int temp=x;
	x=y;
	y=temp;
}
void test_1()
{
	int x=3,y=5;
	swap(x,y);//error C2668: “swap”: 对重载函数的调用不明确.将void swap(int& x,int& y)改成void swap2(int& x,int& y)
	cout<<x<<y<<endl;//35
	int& a=x,b=y;//这里b是int。传值参数。int& a=3,&b=y;//这里b是int&。引用参数
	cout<<a<<b<<endl;//35
	swap2(a,b);
	cout<<x<<y<<endl; //55,只有a改变了。
}

 

异常

10.抛出并捕捉整型异常。

int abc(int a,int b,int c)
{
	if(a<0&&b<0&&c<0)
		throw 1;
	else if(a==0&&b==0&&c==0)
		throw 2;
	return a+b*c;
}

void test_10()
{
	try
	{
		cout<< abc(2,0,2)<<endl;
		cout<< abc(-2,0,-2)<<endl;
		cout<< abc(0,0,0)<<endl;
	}

	catch(exception& e)
	{ 
		cout<<"aa "<<endl;
	}
	
	catch(int e)
	{ 
		if (e==2)
		{
			cout<<"e==2 "<<endl;	
		}

		if (e==1)
		{
			cout<<"e==1 "<<endl;	
		} 
	} 

	catch(...)
	{ 
		cout<<"..."<<endl;
	}
}

输出 

 如果把catch(..)放在最前面会报错。error C2311: “int”: 在行 41 上被“...”捕获 

因为这是捕获所有的,所以一般放最后。

	catch(...)
	{ 
		cout<<"..."<<endl;	
		system("pause");
		return 1;
	}
	catch(int e)
	{ 
		
		if (e==2)
		{
			cout<<"e==2 "<<endl;	
		}

		if (e==1)
		{
			cout<<"e==1 "<<endl;	
		}
		
		system("pause");
		return 1;
	}

 

posted @ 2018-07-24 23:34  lightmare  阅读(4236)  评论(0编辑  收藏  举报