开发者

Using declaration (Derived class)

开发者 https://www.devze.com 2023-01-12 11:48 出处:网络
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?
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(){}

Is it because, B1::fb() is treate开发者_运维知识库d 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-

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.


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).

In your example, B2::fb() hides the B1::fb() introduced by the using declaration.

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:

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; };
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号