代码之家  ›  专栏  ›  技术社区  ›  Kyle

解决命名空间冲突

  •  5
  • Kyle  · 技术社区  · 15 年前

    我有一个命名空间,其中有很多我使用的符号,但我想覆盖其中一个:

    外部库.h

    namespace LottaStuff
    {
    class LotsOfClasses {};
    class OneMoreClass {};
    };
    

    My.Fix.h文件

    using namespace LottaStuff;
    namespace MyCustomizations
    {
    class OneMoreClass {};
    };
    using MyCustomizations::OneMoreClass;
    

    MyoFiel.CPP

    int main()
    {
        OneMoreClass foo; // error: reference to 'OneMoreClass' is ambiguous
        return 0;
    }
    

    如何在不使用1000个单独的“using xxx;”语句替换“using namespace lottastuff”的情况下解决“含糊不清”的错误?

    编辑:另外,假设我不能编辑我的_file.cpp,只能编辑我的_file.h。因此,不可能按照下面的建议将onemoreclass替换为mycustomizations::onemoreclass everywhere。

    2 回复  |  直到 15 年前
        1
  •  10
  •   GManNickG    15 年前

    当你说 using namespace “。

    所以去掉它并使用名称空间。如果需要using指令,请将其放在main中:

    int main()
    {
        using myCustomizations::OneMoreClass;
    
        // OneMoreClass unambiguously refers
        // to the myCustomizations variant
    }
    

    明白什么 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!
    }
    

    一个或另一个将起作用,并将一个放在 main . 如果您发现输入名称空间确实很乏味,请创建一个别名:

    namespace ez = manthisisacrappilynamednamespace;
    
    ez::...
    

    但是 从未 使用 使用命名空间 在头中,可能永远不会在全局范围内。在本地范围内没问题。

        2
  •  3
  •   R Samuel Klatchko    15 年前

    您应该明确指定 OneMoreClass 你想要:

    int main()
    {
        myCustomizations::OneMoreClass foo;
    }
    
    推荐文章