请问: 这个内联函数错在哪儿
请教: 这个内联函数错在哪儿?
// ---- 请先看一下代码: ----
//Test.h
#pragma once
class CTest{
int x;
public:
CTest(void);
~CTest(void);
public:
void SetX(const int xx);
int GetX(void) const;
};
//Test.cpp
#include "Test.h"
CTest::CTest(void){
}
CTest::~CTest(void){
}
inline void CTest::SetX(const int xx){
x=xx;
}
inline int CTest::GetX(void) const{
return x;
}
//Main.cpp
#include "Test.h"
int main(void){
int iValue;
CTest test;
test.SetX(100);
iValue = test.GetX();
}
//-------------------------------------------
以上代码编译通过,但链接通不过.错误提示如下:
正在编译...
Test.cpp
正在链接...
main.obj : error LNK2019: 无法解析的外部符号 "public: int __thiscall CTest::GetX(void)const " (?GetX@CTest@@QBEHXZ),该符号在函数 _main 中被引用
main.obj : error LNK2019: 无法解析的外部符号 "public: void __thiscall CTest::SetX(int)" (?SetX@CTest@@QAEXH@Z),该符号在函数 _main 中被引用
F:\Test\Debug\Test.exe : fatal error LNK1120: 2 个无法解析的外部命令
但是将Test.cpp中GetX()与SetX()前的inline 关键字去掉,就可以了.
像SetX()与GetX()这样简单的函数,我想使用内联函数以提高效率,应该不会错吧?但我不知道我哪儿做错了,请高手指点一下,多谢了.
------解决方案--------------------
内联成员函数的定义放在头文件中是强制的,如果你将内联函数的定义放在.cpp文件中并且在其他.cpp文件中调用它,连接器将给出“unresolved external”错误。
调试通过的代码如下:
Test.h:
// ---- 请先看一下代码: ----
//Test.h
#pragma once
class CTest{
int x;
public:
CTest(void);
~CTest(void);
public:
void SetX(const int xx);
int GetX(void) const;
};
//Test.cpp
#include "Test.h"
CTest::CTest(void){
}
CTest::~CTest(void){
}
inline void CTest::SetX(const int xx){
x=xx;
}
inline int CTest::GetX(void) const{
return x;
}
//Main.cpp
#include "Test.h"
int main(void){
int iValue;
CTest test;
test.SetX(100);
iValue = test.GetX();
}
//-------------------------------------------
以上代码编译通过,但链接通不过.错误提示如下:
正在编译...
Test.cpp
正在链接...
main.obj : error LNK2019: 无法解析的外部符号 "public: int __thiscall CTest::GetX(void)const " (?GetX@CTest@@QBEHXZ),该符号在函数 _main 中被引用
main.obj : error LNK2019: 无法解析的外部符号 "public: void __thiscall CTest::SetX(int)" (?SetX@CTest@@QAEXH@Z),该符号在函数 _main 中被引用
F:\Test\Debug\Test.exe : fatal error LNK1120: 2 个无法解析的外部命令
但是将Test.cpp中GetX()与SetX()前的inline 关键字去掉,就可以了.
像SetX()与GetX()这样简单的函数,我想使用内联函数以提高效率,应该不会错吧?但我不知道我哪儿做错了,请高手指点一下,多谢了.
------解决方案--------------------
内联成员函数的定义放在头文件中是强制的,如果你将内联函数的定义放在.cpp文件中并且在其他.cpp文件中调用它,连接器将给出“unresolved external”错误。
调试通过的代码如下:
Test.h:
- C/C++ code
class CTest { int x; public: CTest(void); ~CTest(void); public: inline void SetX(const int xx){ x=xx; }; inline int GetX(void) const { return x; }; };
------解决方案--------------------
内联函数定义放在头文件里!
- C/C++ code
#include <iostream> using namespace std; #pragma once class CTest{ int x; public: CTest(void); ~CTest(void); public: void SetX(const int xx); int GetX(void) const; }; inline void CTest::SetX(const int xx){ x=xx; } inline int CTest::GetX(void) const{ return x; }