在cpp文件中正确使用名称空间用于函数定义

时间:2014-06-30 13:24:32

标签: c++ namespaces function-pointers

因此,出于某种原因,我遇到了这样的行为,即在我的.h和.cpp文件中为一组函数添加命名空间会破坏我的链接器。我正在使用Visual Studio 2012.这是我的场景(简化)

functions.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文件中:

pointers.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。

functions.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文件中:

pointers.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的链接错误。 使用命名空间中的函数指针是否存在隐含的错误?

1 个答案:

答案 0 :(得分:4)

问题在于您的定义:

int functionA() { return 0; }
int functionB() { return 0; }

位于全局命名空间中;所以他们在那里声明新函数,而不是定义namespace fun中声明的函数。

最好的解决方法是限定定义中的名称:

int fun::functionA() { return 0; }
int fun::functionB() { return 0; }

这比将定义放在命名空间中更好,因为它提供了编译时检查函数是否与其声明匹配。