C 类的内联成员函数应放在哪

今日温习C   Primer的时分,看到了关于C  类的内联成员函数的放置,大概放在头文件中。那么这到底是为什么 呢?仅仅是一种代码标准疑问仍是有必要这样做呢? 下面我就来讲讲我个人的了解吧。要完全了解这个疑问,首要就要了解下函数的声明和界说了。咱们晓得,函数能够 在多处声明,但只能在一个当地界说,否则就会呈现重界说。大多数函数默许是外部连接,而inline函数默许为内部链 接。也就是说inlin http://www.fp1111.info/linked/20130312.do e函数只能在本文件中运用,对其他文件是不行见的。通常咱们运用某个类的时分,都是在文件中加 上该类的头文件,以便咱们能够运用该类的接口。而咱们类的成员函数的完成都是放在相应的.cpp文件中的,而在.h 文件中声明。这样咱们便能够经过.h文件中的成员函数的声明找到其界说,继而运用成员函数了。但若是将inline函数 放在.cpp文件中,那么其只对.cpp文件有用,这样咱们就无法访问它了。所以咱们将其放在类的声明的头文件中,这 样经过包括该头文件来运用它。 下面写个实践的比如来阐明一下,我先把内联函数放到类声明的头文件中: /*test.h*/
#ifndef TEST_H
#define TEST_H

#include 
using std::cout;
using std::endl;

class test
{
public:
	test():x(10){}
	inline void print();
	void display (int y);
private:
	int x;
};

void test::print()
{
	cout << x << endl;
}

#endif /*test.cpp*/
#include 
#include "test.h"
using std::cout;
using std::endl;

void test::display(int y)
{
	cout << x * y << endl;
} /*main.cpp*/
#include 
#include "test.h"
using namespace std;

int main()
{
	test T;
	T.display(10);
	T.print();

	system("pause");
	return 0;
} 运转成果正常,下面来看看将内联函数放到.cpp中去: /*test.h*/
#ifndef TEST_H
#define TEST_H

#include 
using std::cout;
using std::endl;

class test
{
public:
	test():x(10){}
	inline void print();
	void display (int y);
private:
	int x;
};

#endif /*test.cpp*/
#include 
#include "test.h"
using std::cout;
using std::endl;

void test::print()
{
	cout << x << endl;
}

void test::display(int y)
{
	cout << x * y << endl;
} 测试函数和上面的main.cpp是相同的。这是呈现了过错: error LNK2019: 无法解析的外部符号 "public: void __thiscall test::print(void)" (?print@test@@QAEXXZ),该符号在函 数 _main 中被引证。若是我将测试函数改为: int main()
{
	test T;
	T.display(10);
	//T.print();

	system("pause");
	return 0;
} 那么运转成果正常。从此能够得出结论:内联函数放在头文件或许.cpp中都是没有错的,但若是咱们需要在程序中访 问它,那么就有必要将其放在头文件中。 http://www.fpnanchang.com/linked/20130312.do 
posted @ 2013-03-13 10:20  chinadiy197601  阅读(339)  评论(0编辑  收藏  举报