10.对于不包含循环的简单函数,建议用inline关键字声明为"inline内联函数",编译器将内联函数调用用其代码展开,称为“内联展开”,这样可以避免函数调用开销,提高程序执行效率。
#include <iostream>
#include <cmath>
using namespace std;
inline double distance(double a,double b){ //内联函数
return sqrt(a * a + b * b);
}
int main() {
double k = 4,m = 1;
//下面2行将产生同样的代码
cout << distance (k,m) << endl;
cout << sqrt(k * k + m* m) << endl; //运用内联函数直接用程序里的代码替换成函数调用
return 0;
}
11.通过try-catch处理异常情况。把正常代码放在try块,在catch中捕获try块抛出的异常。
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main(){
int a,b;
cout << "Type a number:";
cin >> a;
cout << endl;
try { //对try中代码块可能出出现的异常情况进行监测
if(a > 100) throw 100;
if(a < 10) throw 10; //抛出异常对象
//throw a / 3;
throw "hello";
}
catch (int result) { //如果是整数类型就捕获异常
cout<< "Result is:" << result << endl;
b = result + 1;
cout << "b contains: " << b << endl;
}
//捕获字符串异常需要这样:
catch(char * s){
cout << "xixi" << string(s) << endl; //这里要转化成c语言的字符串
}
cout << endl;
char zero[] = "zero";
char pair[] = "pair";
char notprime[] = "not prime";
char prime[] = "prime";
try { //根据不同情况抛出不同字符串
if (a == 0) throw zero;
if ((a / 2) * 2 == a) throw pair;
for (int i = 3; i <= sqrt (a); i++){
if ((a / i) * i == a) throw notprime;
}
throw prime;
}
catch (char *conclusion){
cout<< "异常结果是:" << conclusion << endl;
}
catch (...) { //抛出的异常与上述情况不匹配,表示所有的异常
cout << "其他异常情况都在这里捕获" << endl;
}
cout << endl;
retuen 0;
}
结果:输入一个数字14,被 字符串异常给捕获了,所以会输出"xixi",也会抛出异常hello,接下来执行下面的会捕获到pair异常。