相关疑难解决方法(0)

为什么类成员函数内联?

我想我之前已经问过我的问题了,我确实读了它们但仍然很少混淆,因此要求说清楚.

The C++ standard says all member functions defined inside class definition are inline

我也听说编译器可以忽略函数的内联.在上述情况下是否会成立,或者如果在类定义中定义,它将始终内联?

此外,这个设计背后的原因是什么,使所有函数在类定义中内联定义?内联与源文件和头文件有什么关系?

更新:所以如果不进行内联,应该总是在课外定义它们的功能,对吧?

JohnB的更新2: 在类定义中声明的两个函数永远不能互相调用,因为它们必须包含另一个函数的整个主体.在这种情况下会发生什么?(已由Emilio Garavaglia回答)

c++ compiler-construction inline class function

28
推荐指数
3
解决办法
9891
查看次数

为什么不能在 .cpp 文件中内联函数定义?

为什么不能在 .cpp 文件中内联函数或类成员函数定义?例如,在我下面的测试示例中,如果我尝试在 cpp 文件中内联函数或类成员定义,链接器会给我一个未定义的引用错误:

测试.h

void print();

class A
{
    public:
        void print() const;
};
Run Code Online (Sandbox Code Playgroud)

测试.cpp

#include <test.h>

inline void print()
{
    // implementation
}

inline void A::print() const
{
    // implementation
}
Run Code Online (Sandbox Code Playgroud)

主程序

#include <test.h>

int main(int argc, char** argv)
{
    print(); // undefined reference to `print()'
    A a;
    a.print(); // undefined reference to `A::print() const'

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我在这里阅读了一些答案,但我仍然不确定它是如何工作的。

c++ linker inline inline-functions

1
推荐指数
1
解决办法
2102
查看次数