【发布时间】: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++