3

你好我有其中包括内联函数,当我尝试用谷歌测试测试这个类时,我有如下错误:

 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());
}

我需要做什么?我阅读了手册,但看不到如何解决此错误。

4

2 回答 2

4

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:

class Math
{
public:
    Math(void);
    double returnPi() { return 3.14; } // no need to specify inline here
    ~Math(void);
};

And remove the definition for returnPi() from your source file.

Note that you could also have done:

class Math
{
public:
    Math(void);
    double returnPi();
    ~Math(void);
};


inline double Math::returnPi() { return 3.14; } // inline is mandatory here to avoid respecting the "One Definition Rule"

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": the inline function must have the same definition in all translation units.

于 2011-04-29T14:22:45.133 回答
0

Are you sure you are compiling the class' CPP file as part of the project? This should be fine.

于 2011-04-29T14:30:36.123 回答