2012-03-24 137 views
2

可能重复:
Scoped using-directive within a struct/class declaration?
Why “using namespace X;” is not allowed inside class/struct level?为什么我不能在C++结构体中使用命名空间指令?

我想向大家介绍只的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”将数据成员或函数从基类引入当前类。因此,当我写一个struct声明中使用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 
} 

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

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

+2

请**不要**在编辑问题时删除自动插入的“可能重复”链接。我知道你更新了,以解释为什么你认为它不是*建议问题的重复,这是完全可以接受/鼓励的行为。但是,您应该让您的编辑碰到问题并吸引注意列表中的用户重新公开投票,或者使用“标志”链接要求版主根据您的更新检查并重新打开投票。删除自动插入的链接是非常不鼓励的;系统将在重新打开时将其删除。 – 2012-03-25 08:01:17

+0

(如果在这种情况下删除它是一个意外 - 即,您的编辑时间相撞 - 然后我为严厉的声音道歉,请将它作为未来的好建议!:-)) – 2012-03-25 08:02:35

回答

2

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

struct Father 
{ 
    typedef std::string string; 

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

它只是没有被不幸的是,语言允许的,但有一个变通方法:

namespace Father_Local 
{ 
    using std::string; 

    struct Father 
    { 
     //... 
    }; 
} 

using Father_Local::Father; 

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

using namespace boost::multi_index; 

那里,并保存在头文件中的打字和杂乱的负载。这些都不影响其余的代码 - 父进程通过使用在最后被导入到它的适当的命名空间,一切正常。

相关问题