从C到C++(内联函数-异常处理)

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 = 6, m = 9;
	// 下面2行将产生同样的代码:
	cout << distance(k, m) << endl;
	cout << sqrt(k * k + m * m) << endl;

	return 0;
}

注意:使用了内联函数,编译器不一定会将其内联展开用代码替换掉,编译器将根据内联函数的代码情况进行展开,比如内联函数中有循环语句或者代码较多,编译器可能就不会进行内联展开

  1. 通过 try-catch处理异常情况
    正常代码放在try块,catch中捕获try块抛出的异常
    一个程序运行的时候可能学出错,在c++中将整
    try:抛出异常 catch:捕获异常
    (不好理解,代码多了会比较乱,基本不用。。。)
#include <iostream> 
#include <cmath> 
using namespace std;

int main ()
{
   int a, b;

   cout << "Type a number: ";
   cin >> a;
   cout << endl;

   try 
   {
      if (a > 100) throw 100;
      if (a < 10)  throw 10;       //抛出 
      throw "hello";
   }
   catch (int result)
   {
      cout << "Result is: " << result << endl;
      b = result + 1;
      
   }
   catch (char * s)
   {
	   cout << "haha " << s << endl;
   }

   cout << "b contains: " << b << endl;

   cout << endl;

   // another example of exception use:

   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;

   return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章