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