inline 内联函数可以避免函数重定义问题
在.h中定义了和main函数中一样的函数,在返回值前面添加修饰关键字inline即可.
.h中的生命和.cpp中的实现
1 #if !defined(AFX_STDAFX_H__CF8E6B35_199B_45D0_9F2A_929A26911DD2__INCLUDED_) 2 #define AFX_STDAFX_H__CF8E6B35_199B_45D0_9F2A_929A26911DD2__INCLUDED_ 3 4 #if _MSC_VER > 1000 5 #pragma once 6 #endif // _MSC_VER > 1000 7 8 #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers 9 10 #include <stdio.h> 11 12 13 inline void Fun(); 14 15 16 // TODO: reference additional headers your program requires here 17 18 //{{AFX_INSERT_LOCATION}} 19 // Microsoft Visual C++ will insert additional declarations immediately before the previous line. 20 21 #endif // !defined(AFX_STDAFX_H__CF8E6B35_199B_45D0_9F2A_929A26911DD2__INCLUDED_)
1 #include "stdafx.h" 2 #include <iostream.h> 3 4 // TODO: reference any additional headers you need in STDAFX.H 5 // and not in this file 6 7 inline void Fun() 8 { 9 cout << " .h Fun()" << endl; 10 }
main中的函数inline void Fun();
1 #include "stdafx.h" 2 #include <string.h> 3 #include <stdlib.h> 4 #include <iostream.h> 5 6 7 // inline void Fun(); 8 9 inline void Fun() 10 { 11 cout << "Main() Fun()" << endl; 12 } 13 14 void Fun2(int nData = 2) 15 { 16 17 } 18 19 20 int main(int argc, char* argv[]) 21 { 22 23 void Fun3(int&); 24 25 Fun(); 26 Fun2(3); 27 28 int nData = 4; 29 30 Fun3(nData); 31 32 cout << nData << endl; 33 34 return 0; 35 } 36 37 void Fun3(int& nData ) 38 { 39 nData = 90; 40 // cout << nData << endl; 41 }
Fun3(int&);函数调用的时候引用,在函数中更改了数值之后,穿进去的变量的值也会更改.