[英]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.