我有类似的情况,如下所述:
我有一个头文件first.h
它有一个功能:
char* getName();
和具有函数定义的相关cpp文件first.cpp
char* getName(){return "first";}
和第二个头文件second.h 它具有以下功能:
char* getName();
关联的cpp文件second.cpp
有函数定义
char* getName(){return "second";}
现在有一个 main()
函数:
#include "first.h"
#include "second.h"
int main(){
return 0;
}
当我包含那些 .h
文件时,编译器在函数 getName()
处给出错误,因为它存在冲突。
如何在不更改.h 文件
的情况下摆脱这个问题
最佳答案
您可以在包含这些头文件时使用命名空间:
在你的cpp文件中:
namespace first
{
#include "first.h"
}
namespace second
{
#include "second.h"
}
然后你可以使用如下函数:
...
first::getName();
second::getName();
...
编辑:感谢 Jens 的评论,这仅在函数内联时有效。如果函数不是内联的并且您确实无法更改头文件,则可以为这些函数创建“包装器”头文件:
文件 wrapper-first.h:
namespace first
{
char* getName();
}
文件 wrapper-first.cpp:
#include "wrapper-first.h"
#include "first.h"
char* first::getName()
{
return ::getName();
}
...并为第二个头文件创建相同的文件。然后您只需将 wrpper-include 文件包含在您的 cpp 文件中并使用上面的代码。
关于c++ - 如何避免 C++ 中两个库的变量/函数冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32582933/