使用类成员的声明应该是成员声明(C ++ 2003) [英] Using declaration for a class member shall be a member declaration (C++2003)
问题描述
第7.3.3段。的C ++ 2003标准规定
Paragraph 7.3.3. of C++2003 standard states that
使用类成员的声明是成员声明。
Using declaration for a class member shall be a member declaration.
这意味着以下语法错误:
This means that the following gives a syntax error:
struct S1
{
static int var1;
};
using S1::var1;
以下编译正确:
namespace N2
{
int var2;
}
using N2::var2;
有没有人知道背后的理由(如果有)?
Does anybody know the rationale (if any) behind that?
甚至,标准给出了struct的静态数据成员的显式示例,并指出它应该导致语法错误。 MS C ++给出此错误:
Even more, the standard gives explicit example with static data member of the struct and tells that it should cause syntax error. MS C++ gives this error:
cpptest1.cxx(9):error C2885:'S1 :: var1':not-在非类范围的声明
cpptest1.cxx(9) : error C2885: 'S1::var1': not a valid using-declaration at non-class scope
仍然不清楚为什么应该禁止。
It is still not clear why this should be banned.
推荐答案
它不工作的原因是因为标准禁止它。请特别注意示例中的 s
:
The reason it doesn't work is simply because the Standard forbids it. Pay special attention to s
in the example:
作为解决方法,您可以说:
As a workaround, you can say:
auto& var = S1::var;
使标准(因此所有编译器)更加复杂,以处理具有方便的解决方法的异常情况只是不通过成本效益测试。
Making the Standard (and therefore all compilers) more complicated to handle an unusual case that has a convenient workaround just doesn't pass the cost-benefit test.
这篇关于使用类成员的声明应该是成员声明(C ++ 2003)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!