C ++内联类方法会导致未定义的引用 [英] C++ inlining class methods causes undefined reference

查看:614
本文介绍了C ++内联类方法会导致未定义的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试内联我的一个类的方法时,我得到一个编译器错误。它的工作原理,当我拿走inline关键字。



以下是一个简化示例:



main.cpp:

  #includemy_class.h

int main(){
MyClass c;
c.TestMethod();

return 0;
}

my_class.h: b
$ b

  class MyClass {
public:
void TestMethod();
};

my_class.cpp:

  #includemy_class.h

inline void MyClass :: TestMethod(){
}

我尝试编译:

  g ++ main.cpp my_class.cpp 

我得到错误:

  main.cpp :( .text + 0xd):未定义引用`MyClass :: TestMethod()'
/ pre>

如果我拿走inline,一切都很好。导致此问题的原因是什么? (我应该如何内联类方法?是否可能?)



谢谢。

解决方案

内联函数的主体需要在头中,以便编译器可以在任何需要的地方替换它。请参阅:如何告诉编译器内联成员函数?


I'm getting a compiler error when I try to inline a method of one of my classes. It works when I take away the "inline" keyword.

Here's a simplified example:

main.cpp:

#include "my_class.h"

int main() {
  MyClass c;
  c.TestMethod();

  return 0;
}

my_class.h:

class MyClass {
 public:
  void TestMethod();
};

my_class.cpp:

#include "my_class.h"

inline void MyClass::TestMethod() {
}

I try compiling with:

g++ main.cpp my_class.cpp

I get the error:

main.cpp:(.text+0xd): undefined reference to `MyClass::TestMethod()'

Everything is fine if I take away the "inline". What's causing this problem? (and how should I inline class methods? Is it possible?)

Thanks.

解决方案

The body of an inline function needs to be in the header so that the compiler can actually substitute it wherever required. See this: How do you tell the compiler to make a member function inline?

这篇关于C ++内联类方法会导致未定义的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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