c++ - 为什么我们不能在类中声明命名空间别名?

标签 c++ namespaces

在类中声明命名空间别名似乎是不可能的;但是我们可以在函数级别这样做(使用 g++ 4.3.4 测试):

namespace A
{
}

class C
{
  namespace N = A; // error: expected unqualified-id before `namespace'
};

class D
{
  void f();
};

void D::f()
{
  namespace N = A; // OK
}

知道为什么存在这样的限制吗?这似乎与可以在类中声明的 typedef 不太一致。

最佳答案

根据 C++ 标准 3.3.6

The following rules describe the scope of names declared in classes.

1) The potential scope of a name declared in a class consists not only of the declarative region following the name’s declarator, but also of all function bodies, default arguments, and constructor ctor- initializers in that class (including such things in nested classes). ...........

因此,您只能在类范围内声明此列表中的内容。在类范围内声明其他任何内容都是无效的。不仅是命名空间联盟,还有命名空间。例如

class myClass
{
    //compilation error !!!
    namespace myNamespace
    {
    }
    using namespace std;//another compilation error
}

编辑:

Any idea why such a restriction exists ? This doesn't seem very consistent with typedefs which can be declared inside a class.

因为在类中使用 typedef 非常有用(例如 vector<int>::iterator ),而对于命名空间来说它是无用的。考虑以下代码

class myClass
{
   namespce N=std;
};

//now let's use N
MyClass::N::vector<int> v;//don't you think, that this syntax is horrible, and useless?????

为了比较,看看它在函数中做了什么

void f()
{
    namespace bnu= boost::numeric::ublas;
    bnu::matrix<int> m;//and now we can use short name bnu
}

对于类,我们可以在 cpp 文件中声明命名空间联盟,并且在类声明中不需要来声明它。

关于c++ - 为什么我们不能在类中声明命名空间别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4884494/

相关文章:

c++ - C++ 中的模板代码块?

c# - Visual Studio 无法识别同一项目中的命名空间

wpf - 当应用程序类型为类库时,未定义的CLR namespace

c++ - 按概率排序 if...else if 语句有什么影响?

c++ - 使用 C++ 创建按钮

c++ - c++ 异常中的 catch(exception) 是什么意思?

php - Composer 不会自动加载

c++ - 在另一个命名空间中使用匿名命名空间中定义的变量

c++ - 命名空间困惑

c++ - Visual Studio 2012 上的计算机错误中缺少 GDAL201.dll