5

Well I'm getting a linker (unresolved external symbol) error when doing the following:

-I have a class "Object" - it is defined in "object.h".

it has a constructor like: explicit Object(double x, /* lots more */);

in file "object.cpp" I want to give that constructor a body: Object::object(double x) : _x(x) {}

This works.. However if I add the keyword "inline" in the "object.cpp" file:

inline Object::Object(double x) : _x(x) {}

suddenly a linker error pops up! "error LNK2019: unresolved external symbol"

Why? - does it mean I can't use inlining with constructors?

EDIT: actually I notice it is the case for all methods. However if I move all methods to the object.h header fil it DOES work. You can't inline function from outside the header file where the object is defined?

EDIT2: alright a big update, I decided to build a quick test case:
main.cpp:

#include "a.h"
int main ()
{
    a t;
    t.test(5);
    return 0;
}

a.h

class a {
public:
    void test (int x);
};

a.cpp

#include <iostream>
#include "a.h"
inline void a::test(int x) {
    std::cout << x << std::endl;
}

This gives the following error:

main.obj : error LNK2019: unresolved external symbol "public: void __thiscall a::test(int)" (?test@a@@QAEXH@Z) referenced in function _main

Removal of the "inline" keyword makes the program work.. As does combining "a.h" and "a.cpp" into 1 file.

I really can't think of more information to give :/

4

3 に答える 3

4

の付いた関数の定義に関するルールを理解する必要がありますinline

関数をマークするinlineということは、プログラム内の複数の翻訳単位で関数を定義できることを意味します (ただし、翻訳単位ごとに 1 回のみ)。ただし、すべての定義は同じでなければならず、関数が使用されるすべての翻訳単位で定義を提供する必要があります。 .

あなたの例では、からの翻訳単位がmain.cpp使用されてa::test(int)いますが、その翻訳単位には定義がありません。からの翻訳単位に定義がありますが、a.cppここではマークされinlineています。これは、からの翻訳単位から定義を除外できないことを意味しますmain.cpp

inlineなぜ定義に追加したいのかわかりませんがa.cpp、それは必要でも役に立たないからです。inline関数定義を共有ヘッダー ファイルに配置できますが、関数をソース ファイルに配置する場合は役に立ちません。

于 2010-11-19T00:11:07.873 に答える
2

You have a lower-case o in the constructor name in the code, whether inline or not. C++ names are case-sensitive.

Try this:

inline Object::Object(double x) : _x(x) {}

I'm not clear what you mean by the /* lots more */ comment in the code you posted. if you have other parameters in this declaration, the constructor's definition has to match that.

于 2010-11-18T23:23:18.790 に答える
0

実装に矛盾があります。このコードがクラス定義内に記述されている場合、"Object::" は必要ありません。これにより、コンパイラ エラーが発生する場合があります。消去してもう一度やり直してください。クラス定義外に書いた場合、ここでインライン宣言はできません。

于 2010-11-18T23:45:52.280 に答える