我今天遇到了一种我不完全了解的行为。我直接进入一个最小的代码示例,并逐步进行说明。
我有2个项目:静态c ++库和控制台应用程序。
静态库项目:
图书馆
#pragma once
namespace foo
{
int testFunc();
class StaticLibClass
{
public:
static int testMemberFunc();
};
}
库.cpp
#include "Library.h"
using namespace foo;
// just some functions that don't do much
int testFunc()
{
return 10;
}
int StaticLibClass::testMemberFunc()
{
return 11;
}
控制台应用程序项目:
main.cpp
#include "library.h"
using namespace foo;
void main()
{
// calling this function reslts in LNK2019: unresolved external symbol...
testFunc();
// this function works just fine
StaticLibClass::testMemberFunc();
}
如您所见,类的静态成员函数可以正常工作。但是,单个testFunc会导致链接器错误。为什么是这样?
解决该问题的方法是,不要在Library.cpp文件中使用“ using”,而是将其包装在命名空间中,如下所示:
解决此问题的更改:
库.cpp
#include "Library.h"
namespace foo
{
// just some functions that don't do much
int testFunc()
{
return 10;
}
int StaticLibClass::testMemberFunc()
{
return 11;
}
}
您可能需要将实现函数/方法的主体包装在与原始标头匹配的名称空间语句中,或者可以使用完全合格的名称,这可能是更好的C ++样式:
#include "Library.h"
// just some functions that don't do much
int foo::testFunc()
{
return 10;
}
int foo::StaticLibClass::testMemberFunc()
{
return 11;
}
您不需要使用命名空间foo;在这个版本中。实现这两种方法的主体时,您已经在名称空间'foo'中,但是根据该名称空间中的其他类型,它可能很方便。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句