質問

We have:

class A {
public:
    int f();
    int f(int);
  //...
};
class B {
public:
    int f();
    int f(int);
  //...
};
class AB : public A, public B {
public:
    long f(double, double);
  //...
};

A::f(), A::f(int), B::f(), B::f(int) are now hidden in class AB, and I want to use only A::f() and B::f(int) as if they weren't hidden:

AB ab;
ab.f();  // ab.A::f()
ab.f(1); // ab.B::f(1)

Is there a simpler way to achieve this than by writing the following code?

class AB : public A, public B {
public:
  //...
    int f() {return A::f();}
    int f(int x) {return B::f(x);}
};

I thought of the using keyword but it doesn't distinguish between methods with the same name and different signatures.

役に立ちましたか?

解決

The only way is to declare them and call the base class function that you want as you wrote.

You might have thought about using in some weird way "using" ex: using A::f; but you inherit all function signatures with the same and you cannot specify a single one.

The thing in AB class declaration is:

  • With just the inheritance

You got the interface and implementation from both base class you will have a error when calling to a method that is common on both of them(Note!Even if the signature is not the same). theABVar.A::f(); will give you:

Error:"request for member 'f' is ambiguous"

But you can solve this with theABVar.A::f();(isn't this cool? :D)

  • When you add a method with the same name that in both base classes

The members in the base classes got hidden, therefore, a call to the method is not ambiguous any more.
But to call method on base class you should do the same trick than before.

theABVar.f(); will give you

Ettor: no matching function for call to 'AB::f()'

  • When you try to use "using" for base class functions You will get on compilation time, even if you don't use the function:

    using A::f; using B::f;

using declaration 'using B::f' conflicts with a previous using declaration

Any way, think twice about what you are doing.
You want a function, that depending on the number/type of arguments it calls to a member of a different base class?. I can not imagine a lot of situations where that makes sense.

--------------Conclusion---------------

  1. Think twice about what you are doing. Hiding methods is not usually good.
  2. In your first example Clients can use explicit calls(they will be able to access all public members) theABVar.A::f(), theABVar.A::f(3), theABVar.B::f(), theABVar.B::f(3), theABVar.AB::f(3.0,3.0) and theABVar.f(3.0,3.0) .
  3. You can create the functions you need as you specified(there is no simpler thing), but remember that clients can still call you base functions!
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top