为什么必须内联在类外部(但在头文件中)定义的类成员函数? [英] Why do class member functions defined outside the class (but in header file) have to be inlined?

查看:196
本文介绍了为什么必须内联在类外部(但在头文件中)定义的类成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了关于内联的两种含义的现有答案,但是我仍然很困惑.

I have read existing answers on the two meanings of inline, but I am still confused.

假设我们具有以下头文件:

Let's assume we have the following header file:

// myclass.h

#ifndef INCLUDED_MYCLASS
#define INCLUDED_MYCLASS

class MyClass
{
   public:
      void foo(); // declaration
};

inline void MyClass::foo()
{
    // definition
}

#endif

为什么必须使用inline显式定义在文件的类之外定义的void foo()?

Why does void foo() which is defined outside the class in the file, have to be explicitly defined with inline?

推荐答案

这是因为您在头文件中定义了MyClass::foo.或更抽象一点,该定义将以多个翻译单元(每个包含标头的.cpp文件)出现.

It's because you defined MyClass::foo in a header file. Or a bit more abstract, that definition will be present in multiple translation units (every .cpp file that includes the header).

程序中一个变量/函数的定义不止一个,这违反了一个定义规则,该规则要求每个变量/函数在一个程序中必须只有一个定义.

Having more than one definition of a variable/function in a program is a violation of the one definition rule, which requires that there must be only one definition in a single program of every variable/function.

请注意,标头防护措施并不能防止这种情况,因为它们仅在您在同一文件中多次包含相同标头时提供保护.

Note that header guards do not protect against this, as they only protect if you include the same header multiple times in the same file.

尽管将函数定义标记为inline,但这意味着跨多个翻译单元的定义始终是相同的. 1 .

Marking the function definition as inline though means that the definition will always be the same across multiple translation units.1.

实际上,这意味着链接器将仅使用MyClass::foo的第一个定义,并在各处使用该定义,而忽略其余的内容

In practice, this means that the linker will just use the first definition of MyClass::foo and use that everywhere, while ignoring the rest,

1 :如果不是这种情况,则说明您的程序格式错误,因此无需任何诊断.

1: If this is not the case your program is ill-formed with no diagnostics required whatsoever.

这篇关于为什么必须内联在类外部(但在头文件中)定义的类成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆