简体   繁体   English

C++:在 class 主体之外定义但包含在 header 保护中的成员函数的 ODR 冲突(如 YouCompleteMe 插件中所示)

[英]C++: ODR violation for member functions defined outside of class body but enclosed within header guard (as shown in YouCompleteMe plugin)

I have a simple header file as shown below.我有一个简单的 header 文件,如下所示。

  #ifndef PERSON_H
  #define PERSON_H

  #include <iostream>
  #include <string>
  using namespace std;

  struct Person {
      string name;
      string address;
      auto get_name() const -> string;
  };

 string Person::get_name() const {  // Function 'get_name' defined in a header file; function definitions in header files can lead to ODR violations
          return this -> name;
  }

  #endif

Question:问题:
Even though the Person::get_name() function is defined outside of the struct Person, this function is defined inside the header guard PERSON_H.即使 Person::get_name() function 是在结构体 Person 之外定义的,这个 function 是在 header 保护内部定义的。 YouCompleteMe tool (presume using g++), it states it violates ODR. YouCompleteMe 工具(假设使用 g++),它声明它违反了 ODR。 Why would it violates ODR?为什么会违反 ODR? This function will never be defined more than once since it's control by header guard PERSON_H.这个 function 永远不会被多次定义,因为它由 header 保护 PERSON_H 控制。 I am not sure if there is a bug in the YouCompleteMe tool because i noticed i don't get the same warning message using visual studio.我不确定 YouCompleteMe 工具中是否存在错误,因为我注意到使用 Visual Studio 时没有收到相同的警告消息。

Any help would be great.任何帮助都会很棒。
Thanks.谢谢。

It can be included in multiple compilation units.它可以包含在多个编译单元中。 If you mark the definition inline it should be happy.如果您将定义标记为inline ,它应该很高兴。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在类主体外部定义的C ++成员函数的编译 - Compilation of C++ member functions defined outside the class body 如果在结构体外定义C ++结构成员函数定义有差异吗? - C++ struct member functions definitions have differences if they are defined outside the struct body ? 基本 ODR 违规:.h 文件中的成员函数 - Basic ODR violation: member functions in .h files 在 C++ 中,为什么必须在类外部定义类成员函数以便单独编译? - In C++, why must class member functions be defined outside class for separate compilation? C ++未定义对头文件外部定义的成员函数的引用 - c++ undefined reference to member function defined outside of header file 在类体外定义的成员函数上的sfinae - sfinae on member function defined outside of class body C ++-在模板类之外但在标头中定义成员函数 - C++ - Define member function outside template-class but in header 在类定义中定义的成员函数是否与在C ++中其他地方定义的成员函数的编译方式不同? - Are member functions defined in a class definition compiled differently than member functions defined elsewhere in C++? 在“类定义”中定义的C ++成员函数中隐式“内联” - Is “inline” implicit in C++ member functions defined in class definition 为什么在类之外(但在头文件中)定义的类成员函数必须内联? - Why do class member functions defined outside the class (but in header file) have to be inlined?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM