使用'using'关键字将继承的构造函数公开 [英] Use of 'using' keyword to make inherited constructor public

查看:163
本文介绍了使用'using'关键字将继承的构造函数公开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图测试我的类的受保护的方法和构造函数。为此,我试图将其子类化,然后使用关键字C / C ++ 11 将其成员重新导出为public:

I am trying to test protected methods and constructors of my class. For this purpose, I tried to subclass it, and re-export its members as public with C++11 using keyword:

class Foo {
  protected:
   Foo(int i) {}
   void run() {}
};

class TestableFoo : public Foo {
  public:
   using Foo::Foo;
   using Foo::run;
};

int main() {
  TestableFoo foo(7);
  foo.run();
}


$ b <

However, both g++ and clang++ fail to compile it, producing the following error:

test.cpp:13:15: error: ‘TestableFoo::TestableFoo(int)’ is protected
    using Foo::Foo;
               ^
test.cpp:18:16: error: within this context
   TestableFoo foo(7);
                    ^

TestableFoo构造函数仍然受保护,即使 / code>方法变为public(我单独确认)。为什么会这样呢?我可以理解决策(继承与覆盖可见性),但为什么在方法和构造函数之间存在不一致?

TestableFoo constructor is still protected, even though run method becomes public (I confirmed it separately). Why is that so? I could understand either decision (inheriting vs. overwriting visibility), but why is there an inconsistency between methods and constructors?

推荐答案

标准明确声明继承的构造函数保留其访问级别:

The Standard explicitly states that inherited constructors retain their access levels:

12.9继承构造函数[class.inhctor]


1隐式命名构造函数的using-declaration(7.3.3)
声明一组继承构造函数。
的候选集合从使用声明
中命名的 X 类中继承的构造函数由实际构造函数和名词构造函数组成,结果为
从默认参数的转换如下:

1 A using-declaration (7.3.3) that names a constructor implicitly declares a set of inheriting constructors. The candidate set of inherited constructors from the class X named in the using-declaration consists of actual constructors and notional constructors that result from the transformation of defaulted parameters as follows:

[已省略的案例列表]

[list of cases omitted]


4 这样声明的构造函数具有与X 中对应的
构造函数相同的访问权限。如果 X
中的相应构造函数已删除(8.4),则删除它。

4 A constructor so declared has the same access as the corresponding constructor in X. It is deleted if the corresponding constructor in X is deleted (8.4).

你可以直接调用它:

TestableFoo(int i) : Foo(i) { }

这篇关于使用'using'关键字将继承的构造函数公开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆