私有继承使用指令,重载?

时间:2011-01-12 20:32:13

标签: c++ inheritance

我在一个项目中使用私有继承,在“使用”实现“-sense”。基类定义operator [],这是我想要使用的功能。因此,我有

class A : private B {
    using B::operator[];
    // ...
};

但是,如何控制运营商[]的版本?事实上,我需要多个const和非const版本。这可以实现吗?

2 个答案:

答案 0 :(得分:6)

我的理解是你的using应该自动引入运营商的所有不同重载。您是否希望将某些重载排除在子类中?在这种情况下,最好将工作分成父级中的几个不同命名的函数,而只需要using个所需的函数。

答案 1 :(得分:2)

这样做符合预期:

class A
{
public:
  int operator[](int idx) { return 0; }
  int operator[](int idx) const { return 1; }
};

class B : public A
{
public:
  using A::operator[];

  void opa() { cout << operator[](1) << endl; }
  void opb() const { cout << operator[](1) << endl; }
};

int main(void)
{
  B b;
  b.opa();
  b.opb();

  const B d = B();
  cout << d[1] << endl; // should trigger the const version of operator[]
  return 0;
}

换句话说,适当的const /非const版本被注入B。注意:如果未提供const版本,则会收到编译器错误(无论继承是私有还是公共,这都有效。)

相关问题