天天看點

ca64a_c++_内聯函數inline

//頭檔案中:

/*ca64a_c++_内聯函數

内聯函數避免函數調用的開銷
把内聯函數放入頭檔案中,直接定義,不用聲明。與普通函數不一樣,普通函數定義寫在源檔案中。


注意:
内聯說明對于編譯器來說隻是一個建議,編譯器可以選擇忽略這個建議,對于短小的函數,會展開。
遞歸函數、大函數不太可能在調用點内聯展開,是以一般不用inline

帶有inline的函數:内聯函數,加快速度。在編譯的時候就展開:
比如:inline int sum(int a, int b) 已經是内聯函數
編譯後:在main函數調用時。
cout << sum(x[i], y[i]) << endl;此語句編譯後:實際就沒有調用sum函數。
直接執行的是:cout << x[i]+y[i] << endl;
txwtech

*/
#include <iostream>
#include <string>
#include "ca64a.h"
using namespace std;
//帶有inline的函數:内聯函數,加快速度。在編譯的時候就展開:
//比如:inline int sum(int a, int b) 已經是内聯函數
//inline int sum(int a, int b)//對于短小的函數,會展開。
//{
//	return a + b;
//}
//inline const string &shortString(const string &s1,const string &s2)
//{
//	return s1.size() < s2.size() ? s1 : s2;
//}
//inline bool isShorter(const string &s1, const string &s2)
//{
//	return s1.size() < s2.size();
//}
int main()
{
	int x[] = { 1,2,3,4,5,6,7,8,9 };
	int y[] = { 1,2,3,4,5,6,7,8,9 };
	for (int i = 0; i < 9; ++i)
		cout << sum(x[i], y[i]) << endl;

	cout << shortString("hello","bill");
	return 0;
}
           
//頭檔案中ca64a.h:
/*
#pragma once //表示在編譯的時候, 這個檔案隻被包含(include)一次,這樣, 可以減少整個編譯過程中打開這個檔案的次數.
與如下效果一樣:頭檔案保護,防止重複包含
#ifndef ca64a_H
#define ca64a_H
.....
#endif
頭檔案中不要用 using namespace std,<iostream>;
字元串直接用std::string方式
*/


#include <string>

#ifndef  CA64A_H //頭檔案保護,防止重複包含
#define CA64A_H

inline int sum(int a, int b)//對于短小的函數,會展開。
{
	return a + b;
}
inline const std::string &shortString(const std::string &s1, const std::string &s2)
{
	return s1.size() < s2.size() ? s1 : s2;
}
inline bool isShorter(const std::string &s1, const std::string &s2)
{
	return s1.size() < s2.size();
}


#endif // ! CA64A_H
           

繼續閱讀