使用声明(派生类) [英] Using declaration (Derived class)
问题描述
struct B1{
int d;
void fb(){};
};
struct B2 : B1{
using B1::d;
using B1::fb;
int d; // why this gives error?
void fb(){} // and this does not?
};
int main(){}
是因为, B1 :: fb()
被视为 B1 :: fb(B1 *)
和B2 :: fb()
被视为 B2 :: fb(B2 *)
?也就是说,隐式参数是否有助于区分它们?
Is it because, B1::fb()
is treated as B1::fb(B1*)
and B2::fb()
treated as B2::fb(B2*)
? That is, does the implicit parameter, help in distinguishing these?
$ 13.3.1 / 4-
$13.3.1/4-
对于通过使用声明将
引入派生的
类的非转换函数,该函数被视为
是
的派生类的成员。定义隐式对象参数
的类型。
For nonconversion functions introduced by a using-declaration into a derived class, the function is considered to be a member of the derived class for the purpose of defining the type of the implicit object parameter.
推荐答案
C ++标准(C ++ 03§7.3.3/ 12)解释:
The C++ standard (C++03 §7.3.3/12) explains:
当使用声明出现时名称从基类到派生类范围中,派生类中的成员函数会覆盖和/或隐藏基类中具有相同名称和参数类型的成员函数(而不是冲突)。
When a using-declaration brings names from a base class into a derived class scope, member functions in the derived class override and/or hide member functions with the same name and parameter types in a base class (rather than conflicting).
在您的示例中, B2 :: fb()
隐藏 B1 :: fb( )
由using声明引入。
In your example, B2::fb()
hides the B1::fb()
introduced by the using declaration.
至于为什么两个 u都格式不正确请在
和 B2
的定义中使用B1 :: d; int d;
C ++标准(C ++ 03§7.3.3/ 10)解释:
As for why it is ill-formed to have both using B1::d;
and int d;
in the definition of B2
, the C++ standard (C++03 §7.3.3/10) explains:
由于 using-declaration 是声明,对同一声明区域中同名声明的限制也适用于 using-declaration。
Since a using-declaration is a declaration, the restrictions on declarations of the same name in the same declarative region also apply to using-declarations.
因此,它的格式错误是由于以下原因导致的格式错误:它在单个声明性区域中导致两个名称相同的对象:
So, it is ill-formed for the same reason that the following is ill-formed: it results in two objects with the same name in a single declarative region:
struct S { int d; int d; };
这篇关于使用声明(派生类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!