在类中声明命名空间别名似乎是不可能的;但是我们可以在函数级别这样做(使用 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/