【问题标题】:Proper use of namespaces for function definitions in cpp file在 cpp 文件中正确使用命名空间来定义函数
【发布时间】: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 命名空间的函数。它不会使 functionAfunctionB 成为该名称空间的一部分。您实际上已在该文件的全局范围内重新声明了这些函数。

标签: c++ namespaces function-pointers


【解决方案1】:

问题在于你的定义:

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

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

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

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

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

【讨论】:

  • 感谢您快速简洁的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 2018-10-28
  • 2012-01-21
相关资源
最近更新 更多