c++内联函数
在学习c++内联函数的过程中, 编写了如下三个文件:
头文件Test.h (类的声明)
#ifndef _TEST_H_
#define _TEST_H_
#include<iostream>
using namespace std;
class Test
{
public:
int Add(int a,int b)
};
#endif //_TEST_H_
Test.cc (类的定义)
1 #include"Test.h"
2 #include<iostream>
3 using namespace std;
4 inline int Test::Add(int a,int b)
5 {
6 cout<<"a+b="<<a+b<<endl;
7
8 }
测试例子
#include"Test.h"
#include<iostream>
int main ()
{
Test c;
c.Add(4,5);
}
在Linux下编译时出错:
错误如图所示。
然后,我开始了Google之旅,于是,搜索,搜索,再搜索,终于找到了
简单的理解就是,你要把inline定义过的函数在所有你要用到的地方(不同的文件之间)重新定义一遍,而且保证定义相同。下面是stackoverflow上的解释。
英文解释
这样就可以解决这个问题。不过,,好像各方人马都不太建议使用inline ,因为编译器已经越来越洪荒之力了。
还有一个疑问,就是有人认为仅在类声明中用inline定义成员函数的方法即可。然而我试了一下,没有成功。