解决命名空间冲突

Kyl*_*yle 5 c++ namespaces

我有一个名称空间,我使用了大量的符号,但我想覆盖其中一个:

external_library.h

namespace LottaStuff
{
class LotsOfClasses {};
class OneMoreClass {};
};
Run Code Online (Sandbox Code Playgroud)

my_file.h

using namespace LottaStuff;
namespace MyCustomizations
{
class OneMoreClass {};
};
using MyCustomizations::OneMoreClass;
Run Code Online (Sandbox Code Playgroud)

my_file.cpp

int main()
{
    OneMoreClass foo; // error: reference to 'OneMoreClass' is ambiguous
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如何解决"模糊"错误而无需使用"使用命名空间LottaStuff"替换千位"使用xxx"; 声明?

编辑:另外,说我不能编辑my_file.cpp,只能编辑my_file.h.因此,如下所示,用MyCustomizations :: OneMoreClass替换OneMoreClass是不可能的.

GMa*_*ckG 10

当你说" using namespace" 时,命名空间的整个点就会失败.

所以把它拿出来并使用命名空间.如果你想要一个using指令,把它放在main中:

int main()
{
    using myCustomizations::OneMoreClass;

    // OneMoreClass unambiguously refers
    // to the myCustomizations variant
}
Run Code Online (Sandbox Code Playgroud)

了解using指令的作用.你拥有的基本上是这样的:

namespace foo
{
    struct baz{};
}

namespace bar
{
    struct baz{};
}

using namespace foo; // take *everything* in foo and make it usable in this scope
using bar::baz; // take baz from bar and make it usable in this scope

int main()
{
    baz x; // no baz in this scope, check global... oh crap!
}
Run Code Online (Sandbox Code Playgroud)

一个或另一个将工作,并将一个放在范围内main.如果您发现键入的命名空间非常繁琐,请创建别名:

namespace ez = manthisisacrappilynamednamespace;

ez::...
Run Code Online (Sandbox Code Playgroud)

永远不要using namespace在标题中使用,可能永远不会在全球范围内使用.它在本地范围内很好.