模糊函数调用复杂的继承情况

时间:2012-07-11 19:26:32

标签: c++ inheritance ambiguous

我有以下代码: -

#include <iostream>
#include <vector>

using namespace std;

template <typename I>
class A {
  public:
    void f (I* i) {
      lis.push_back(i);
    }
    vector <I*> lis;
};

class B {
  public:
    int b;
};

class C {
  public:
    double c;
};

class D : public A<B>,
          public A<C> {
  public:
    void g () {
      cout<<"g\n";
    }
};

class E : public B, public C {
  public:
    float e;
};

int main() {
  E* e;
  D d;
  B* b = (B*) e;
  d.f (b);
}

这给我一个错误说: -

ambig.cpp: In function ‘int main()’:
ambig.cpp:42:5: error: request for member ‘f’ is ambiguous
ambig.cpp:9:10: error: candidates are: void A<I>::f(I*) [with I = C]
ambig.cpp:9:10: error:                 void A<I>::f(I*) [with I = B]

关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:7)

class D : public A<B>,
          public A<C> {
  public:
    using A<B>::f;  // <=== use
    using A<C>::f;  // <=== this

标准中详细介绍了使用冗长语言,但简单的规则是:所有成员函数重载必须来自同一个类。