【发布时间】:2014-06-30 13:24:31
【问题描述】:
因此,出于某种原因,我遇到了这样一种行为,即为一组函数添加命名空间到我的 .h 和 .cpp 文件会破坏我的链接器。我正在使用 Visual Studio 2012。这是我的场景(简化)
函数.h
int functionA();
int functionB();
functions.cpp
#include "functions.h"
int functionA() { return 0; }//we could pretend there's actual code here
int functionB() { return 0; }//we could pretend there's actual code here
它的实际用途是在一些cpp文件中:
指针.h
#include "functions.h"
class GetPointers
{
public:
typedef int (*FunctionPointer)(void);
static FunctionPointer funcPointerA() { return &functionA; }
static FunctionPointer funcPointerB() { return &functionB; }
};
嗯,这一切都很好,花花公子。我可以调用 GetPointers 的静态方法并获得一个有效的函数指针。一切都经过测试,一切都很愉快。现在我想我会简单地添加一些命名空间来确保我将来不会再遇到任何问题。所以我简单地修改这三个代码文件来使用命名空间。发生的情况是链接错误,它引用 GetPointers 类的函数 funcPointerA() 和 funcPointerB(),完整的命名空间名称为 functionA 和 functionB。
函数.h
namespace fun {
int functionA();
int functionB();
}
functions.cpp
#include "functions.h"
using namespace fun;
int functionA() { return 0; }//we could pretend there's actual code here
int functionB() { return 0; }//we could pretend there's actual code here
它的实际用途是在一些cpp文件中:
指针.h
#include "functions.h"
namespace fun {
class GetPointers
{
public:
typedef int (*FunctionPointer)(void);
static FunctionPointer funcPointerA() { return &functionA; }
static FunctionPointer funcPointerB() { return &functionB; }
};
}
我没有收到构建错误,只有关于 fun::functionA 和 fun::functionB 的链接错误。 使用命名空间中的函数指针有什么隐含的错误吗?
【问题讨论】:
-
using namespace fun;只允许您使用来自fun命名空间的函数。它不会使functionA和functionB成为该名称空间的一部分。您实际上已在该文件的全局范围内重新声明了这些函数。
标签: c++ namespaces function-pointers