为什么我不能在另一个文件中定义内联成员函数? [英] Why I can't define inline member function in another file?

查看:168
本文介绍了为什么我不能在另一个文件中定义内联成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个文件:



1。 Joy.h

  class Joy 
{
public:
void test ();
};

2。 Joy.cpp

  #includeJoy.h
void Joy :: test(){}

main.cpp

  #includeJoy.h
int main()
{
Joy r;
r.test();
return 0;
}



我尝试使用以下命令编译它们:

  g ++ cpp Joy.cpp 

g ++说:

  main.cpp :(。text + 0x10):未定义的引用`Joy :: test $ b  

谁能告诉我为什么...

如果我不想在.h文件中定义 test()函数,并且仍然希望它是 inline 函数

解决方案

当你定义一个内联成员函数时,你应该在关键字inline前面添加成员函数的定义,定义到头文件中。



当你基本上声明一个函数inline基本上你告诉编译器(如果可能的话)用函数的内容替换调用函数的代码。 。这个想法是函数体可能很小,调用函数比函数本身的开销更多。

为了能够做到这一点,编译器需要在编译调用函数的代码时看到定义,这实质上意味着定义必须驻留在头中,因为调用函数的代码只能访问头文件。



良好阅读:

[ 9.7]你如何告诉编译器内联成员函数?


I have three files:

1. Joy.h

class Joy
{
public:
    void test();
};

2. Joy.cpp

#include "Joy.h"
inline void Joy::test() {}

3. main.cpp

#include "Joy.h"    
int main()
{
    Joy r;        
    r.test();        
    return 0;
}

I try to compile them using:

g++ cpp Joy.cpp

g++ say:

main.cpp:(.text+0x10): undefined reference to `Joy::test()'

Who can tell me why...

How to solve this problem if I don't want to define that test() function in the .h file and still want it to be an inline function?

解决方案

when you define an inline member function, you should prepend the member function's definition with the keyword inline, and you put the definition into a header file.

When you declare a function inline basically You are telling the compiler to (if possible)replace the code for calling the function with the contents of the function wherever the function is called. The idea is that the function body is is probably small and calling the function is more overhead than the body of the function itself.

To be able to do this the compiler needs to see the definition while compiling the code which calls the function this essentially means that the definition has to reside in the header because the code which calls the function only has access to the header file.

Good Read:
[9.7] How do you tell the compiler to make a member function inline?

这篇关于为什么我不能在另一个文件中定义内联成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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