【问题标题】:Scoping with pre-made namespace (C++)使用预制命名空间 (C++)
【发布时间】:2012-01-18 23:52:43
【问题描述】:

为避免从 STL 中确定所有内容的范围,您可以键入

using namespace std;

为避免只限定几件事,您可以键入:

using std::cout;  
using std::cin;

我想编写一个以相同方式运行的库。但是,我希望能够包含特定的函数集合,而不是能够包含特定的类。

所以,例如,我编码:

  • 字符串函数集合
  • 数学函数集合

它们是同一个命名空间的一部分,但我可以包含我想要的块


这是 sudo-ish 代码,但我认为它传达了我的想法:

namespace Everything{
    namespace StringFunctions{
        void str1(string & str);
        void str2(string & str);
        void str3(string & str);
        void str4(string & str);
        void str5(string & str);
    }

    namespace MathFunctions {
        void math1(int & num);
        void math2(int & num);
        void math3(int & num);
        void math4(int & num);
        void math5(int & num);
    }
}

然后我希望能够做类似的事情:

#include "Everything.h"
using Everything::Stringfunctions;

int main(){

    str1("string"); //this works, I can call this!
    math1(111);     //compile error: I've never heard of that function!

    return 0;
}

显然这不起作用,我对如何划分我的图书馆有点困惑。我不想让它们成为类,然后不得不在任何地方使用“点运算符”,但我也不想包含大量的头文件。

也许我做错了。我希望大家可以帮助我在这里采取正确的方法。


编辑:

它的工作原理是:

using namespace Everything::Stringfunctions;

事后看来,这一点非常明显。

【问题讨论】:

  • 你没有把namespace放在你的using之后。
  • +1 “很好”地提出了一个好问题。
  • @stonybrooknick 你应该等待提问者修复他们自己的代码;也许他们没有意识到他们犯了错误。 (虽然不太可能,但最好让他们自己修复代码。)
  • @stonybrooknick 这不是 我的 代码。 :) (或者你是在讽刺......?) 编辑:在这种情况下,这确实是问题所在!奇怪...

标签: c++ namespaces include scope


【解决方案1】:

您在给出的示例中编写库的方式就足够了。

人们可以使用指令using namespace Everything::Stringfunctions 从命名空间Everything::Stringfunctions 中获取每个函数。

【讨论】:

    【解决方案2】:

    无论如何,您都应该考虑将功能拆分为不同的标头,否则您会遇到噩梦般的编译时间。也就是说,我认为 using namespace Everything::Stringfunctions; 应该这样做(其中有额外的 namespace。不过我没有尝试编译)。

    【讨论】:

    • 哦,绝对!为了清楚起见,只是这样写
    【解决方案3】:

    只要您使用using namespace 而不仅仅是using,您想要的似乎就可以了。见here(程序编译并输出'5')。

    【讨论】:

      猜你喜欢
      • 2014-07-17
      • 2013-08-01
      • 2011-05-03
      • 1970-01-01
      • 2010-12-23
      • 2011-07-15
      • 1970-01-01
      • 2011-01-02
      • 1970-01-01
      相关资源
      最近更新 更多