【问题标题】:Why can I not use the namespace directive in c++ struct? [duplicate]为什么我不能在 c++ 结构中使用命名空间指令? [复制]
【发布时间】:2012-04-09 00:54:39
【问题描述】:

可能重复:
Scoped using-directive within a struct/class declaration?
Why “using namespace X;” is not allowed inside class/struct level?

我只想将 std::string 引入结构。 为什么以下被认为是非法的?

#include <iostream>
#include <string>

struct Father
{
    using std::string;

    string sons[20];
    string daughters[20];
};

但奇怪的是,我可以在函数中执行以下操作

int main()
{
    using std::string;
}

更新:C++ 使用具有不同语义的相同关键字。

c++ 使用关键字“using”将数据成员或函数从基类引入当前类。因此,当我在结构声明中使用 std::string 编写时,编译器假设我正在尝试从基类 std 中引入一个成员。但 std 不是基类,而是命名空间。 因此

struct A
{
     int i;
}

struct B:A
{
     using A::i; // legal
     using std::string// illegal, because ::std is not a class
}

同样的“using”关键字也用于访问特定命名空间的成员。

所以,我猜编译器会根据声明的位置来决定“使用”的语义。

【问题讨论】:

  • 不要在您编辑问题时删除自动插入的“可能重复”链接。我知道您更新是为了解释为什么您认为它不是建议问题的重复,这是完全可以接受/鼓励的行为。但是您应该让您的编辑提出问题并吸引在列表中注意到它的用户重新打开投票,或者使用“标记”链接要求版主检查并根据您的更新重新打开它。强烈建议不要删除自动插入的链接;系统会在重新打开时将其删除。
  • (如果在这种情况下删除它是一个意外——也就是说,你的编辑及时发生了冲突——那么我为听起来刺耳的语气道歉。把它当作对未来的好建议吧!:-) )

标签: c++


【解决方案1】:

我不知道你的实际问题的答案,但你可以使用 typedef:

struct Father
{
    typedef std::string string;

    string sons[20];
    string daughters[20];
};

【讨论】:

    【解决方案2】:

    不幸的是,语言不允许这样做,但有一种解决方法:

    namespace Father_Local
    {
        using std::string;
    
        struct Father
        {
            //...
        };
    }
    
    using Father_Local::Father;
    

    这种方法的优点是原则上你可以编写一个 using 指令,例如

    using namespace boost::multi_index;
    

    在那里并为自己节省头文件中的大量输入和混乱。这些都不会影响其余代码 - 父亲通过最后的 using 导入其正确的命名空间,一切正常。

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 2023-03-06
      • 2020-06-06
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多