c++ - 我因为两次定义函数而收到此错误

标签 c++ class oop enums

错误:

CMakeFiles\Final_Project_2nd.dir/objects.a(Tab.cpp.obj): In function `Z8Type2IntNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE':
C:/Users/Andrea/CLionProjects/Final_Project_2nd/Utils.hpp:37: multiple definition of `Type2Int(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
CMakeFiles\Final_Project_2nd.dir/objects.a(main.cpp.obj):C:/Users/Andrea/CLionProjects/Final_Project_2nd/Utils.hpp:37: first defined here

我创建了一个 header Utils.hpp,其中包含两个 enum 和两个函数,并将其包含在需要使用这些东西的任何地方:

enum Types {
    OptionInt,
    OptionFloat,
    [...]
    OptionInvalid
};
enum Commands {
    CommandCreate = OptionInvalid + 1,
    CommandDrop,
    [...]
    CommandInvalid
};
Types Type2Int(string type){
    if(type == "int") return OptionInt;
    if(type == "float") return OptionFloat;
    [...]
    return OptionInvalid;
}
Commands Command2Int(string command){
    if(command == "CREATE") return CommandCreate;
    if(command == "DROP") return CommandDrop;
    [...]
    return CommandInvalid;
}

最佳答案

您在 header 中定义函数,这就是问题所在。 multiple definition in header file

inline 解决方案很好,或者您可以将声明保留在 hpp 文件中并在单独的 cpp 文件中实现它 - 这是最“标准”的解决方案。

关于c++ - 我因为两次定义函数而收到此错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62384260/

相关文章:

javascript - 下拉列表 : call class method by changing

python初始化单独文件中的常量

c++ - 来自命名空间的方法链接

swift 3 : The difference between Public and Internal access modifiers?

c++ - HTML 页面抓取中插入异常、意外的值

c++ - Myhill-Nerode 定理矩阵到自动机

class - 如何将类之间的依赖关系管理到 coffeescript 项目中

C++:对 map 的引用

C++ Virtual Studio Hello World 缺少命令?

java - 包含的对象在何处创建才能被视为组合或聚合,这重要吗?