Using declaration (Derived class)

会有一股神秘感。 提交于 2019-12-08 19:44:04

问题


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

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.


回答1:


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


来源:https://stackoverflow.com/questions/3544824/using-declaration-derived-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!