2

Consider the following code:

In header.h

#pragma once

class someClass
{
public:
    void foo();
};

In header.cpp

#include "header.h"

inline void someClass::foo(){}

In main.cpp

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

int main()
{
    someClass obj;
    obj.foo();
}

Here I get a link error because foo function is defined as inline in header.cpp, if I remove the 'inline' keyword, the compile and run will proceed without errors.

Please tell me why I get link error on this 'inline' function?

4

1 回答 1

3

您编写它的方式,内联适用于当前文件范围。当内联函数位于标头中时,该标头包含在 cpp 文件中,然后该函数在该文件范围内使用的位置内联,因此没有问题。在这种情况下,您的函数仅在定义的地方作为内联函数可用,并且没有其他 cpp 文件看到它,除了作为其类中的常规成员声明,​​因此链接错误。

如果您希望它是内联的,请在标题中添加代码和 inline 关键字。

于 2014-04-20T17:10:29.623 回答