C++中的内联成员函数与非内联成员函数

在C++中内联成员函数与非内联成员函数的可以分为两种情况:

1.如果成员函数的声明和定义是在一起的,那么无论有没有写inline这个成员函数都是内联的,如下:

using namespace std;
class test{
public:
	void fuc() {
		cout << "ok!" << endl;
	}
};
int main(void)
{
	test t, t1;
	t.fuc();
	t1.fuc();

	return 0;
}

  或者:

using namespace std;
class test{
public:
	inline void fuc() {
		cout << "ok!" << endl;
	}
};
int main(void)
{
	test t, t1;
	t.fuc();
	t1.fuc();

	return 0;
}

2.如果成员函数的声明和定义是分开的,那么如果两者中有一个加上了inline都会使成员函数都是内联的,如:

#include <iostream>
using namespace std;
class test{
public:
	inline void fuc();
};
int main(void)
{
	test t, t1;
	t.fuc();
	t1.fuc();

	return 0;
}
void test::fuc(){
	cout << "ok!" << endl;
}

 或:

#include <iostream>
using namespace std;
class test{
public:
	void fuc();
};
int main(void)
{
	test t, t1;
	t.fuc();
	t1.fuc();

	return 0;
}
inline void test::fuc(){
	cout << "ok!" << endl;
}

要想定义非内联成员函数,只有一种方法即:声明和定义都不加inline,如下

#include <iostream>
using namespace std;
class test{
public:
	void fuc();
};
int main(void)
{
	test t, t1;
	t.fuc();
	t1.fuc();

	return 0;
}
void test::fuc(){
	cout << "ok!" << endl;
}

------------------------------------------------------------------------------------------------------------------------------

验证时使用Release版本编译同时在链接选项进行如下配置:

 之后可以查看编译后的汇编代码之间的区别来验证。

原文地址:https://www.cnblogs.com/xxNote/p/4082838.html