0

考虑这段代码

#include <iostream> 
#include <cstdio>
using namespace std;

class Dummy {
public:
    Dummy();
};

inline Dummy::Dummy() {
    printf("Wow! :Dummy rocks\n");
}

int main() {
    Dummy d;
}

这里一切都很好!

现在我做这个修改。我将 Dummy 的声明移至“dummy.h”。

class Dummy {
public:
    Dummy();
};

并在“dummy.cpp”中定义构造函数 Dummy() 如下

#include "dummy.h"
inline Dummy::Dummy() {
    printf("Wow! :Dummy rocks\n");
}

最后,我的主文件为:

#include <iostream> 
#include <cstdio>
#include "dummy.h"
using namespace std;

int main() {
    Dummy d;
}

它编译得很好,但我收到一个链接器错误,抱怨对 Dummy::Dummy() 的未定义引用。

任何见解。

--

4

3 回答 3

3

您必须将所有内联函数(包括方法和构造函数/析构函数)放在一个头文件中,并在其中声明它们。

尽管这段代码应该以任何一种方式工作,main()调用构造函数就好像inline关键字不存在一样。您确定要将目标文件从两个编译单元传递到链接器吗?

于 2010-06-26T15:05:55.093 回答
2

You should think how compiling works at C++ and the idea of separate compiling units used at C++ and encapsulation gained using headers and cpp files.

Look here: http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.6

The inline tells the complier that instead of calling the function to "copy - paste" its code at the place of the function call. When you put the inline definition in a CPP file it won't be visible during linking to other compiled units (its in cpp file not in h file) so the compiler understand from the signature placed at the class that there is no-paramter Con's so it won't implement the default one. But the linker can't find the function body cause it is implemnted inline at the cpp file.

于 2010-06-26T15:26:36.033 回答
0

Try removing the inline specifier from the your implementation file. If my understanding is correct, you can only inline in a header

于 2010-06-26T15:07:49.833 回答