内联函数的 gtest 问题
你好,我有包含内联函数,当我尝试用谷歌测试测试这个类时,我有这样的错误:
error LNK2019: unresolved external symbol "public: double __thiscall Math::returnPi(void)" (?returnPi@Math@@QAENXZ) referenced in function "private: virtual void __thiscall Speed_Math_Test::TestBody(void)" (?TestBody@Speed_Math_Test@@EAEXXZ)
例如我的类(头文件)
class Math
{
public:
Math(void);
inline double returnPi();
~Math(void);
};
我的类(cpp文件)
Math::Math(void)
{}
Math::~Math(void)
{}
double Math::returnPi()
{ return 3.14;}
测试:
TEST(EQ, Math)
{
Math *m=new Math();
EXPECT_EQ(3.14,m->returnPi());
}
我需要做什么?我阅读了手册,但不知道如何解决此错误。
hello i have which include inline function, when i try testing this class with google test, i have error like:
error LNK2019: unresolved external symbol "public: double __thiscall Math::returnPi(void)" (?returnPi@Math@@QAENXZ) referenced in function "private: virtual void __thiscall Speed_Math_Test::TestBody(void)" (?TestBody@Speed_Math_Test@@EAEXXZ)
for example my class(header file)
class Math
{
public:
Math(void);
inline double returnPi();
~Math(void);
};
my class(cpp file)
Math::Math(void)
{}
Math::~Math(void)
{}
double Math::returnPi()
{ return 3.14;}
test:
TEST(EQ, Math)
{
Math *m=new Math();
EXPECT_EQ(3.14,m->returnPi());
}
what i need to do? i read manual but dont see how i can resolved this error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
内联函数应该位于您的头文件中,而不是位于源文件中,因此它实际上可以由调用者(无权访问源文件)内联。
此外,如果您给出了函数的定义,则无需在类声明中指定
inline
。因此,您的标头应变为:
并从源文件中删除
returnPi()
的定义。请注意,您也可以这样做:
如果您想将类声明与函数定义分开,则第二种解决方案很好。
另请注意,
inline
并不保证实际的函数调用将被内联:它强制执行的唯一一件事是您不必遵守“单一定义规则”:inline< /code> 函数在所有翻译单元中必须具有相同的定义。
An inline function should be in your header file, not in your source file so it can actually be inlined by the callers (which don't have access to the source file).
Moreover, you don't need to specify
inline
in your class declaration if you give the definition of the function.So your header should become:
And remove the definition for
returnPi()
from your source file.Note that you could also have done:
The second solution is good if you want to keep the class declaration separate from the function definition.
Also note that
inline
does not guarantees that the actual function calls will be inlined: the only thing it enforces is that you don't have to respect the "One Definition Rule": theinline
function must have the same definition in all translation units.您确定正在将类的 CPP 文件编译为项目的一部分吗?这应该没问题。
Are you sure you are compiling the class' CPP file as part of the project? This should be fine.