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

本文深入探讨了C++中函数参数的正确使用方法,包括引用传递与值传递的区别,以及异常处理机制,通过具体代码示例展示了如何正确地交换两个整数,并介绍了整型异常的抛出与捕捉技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

第一章 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;
	}

 

转载于:https://www.cnblogs.com/lightmare/p/10398836.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值