Pergunta

This is a simple question (I think). I'm just not sure about it and I'm looking for a good solution too :)

Let's say I have this:

class Base {
  public:
    virtual ~Base() {}
    virtual Base& connect(Base &b) = 0;
}

class Derived: public Base {
  public: 
    virtual ~Derived() {}
    virtual Base& connect(Base &b)
    {
      // do_something
    }
}

// Name is a class that is basically a String and assign it to any A or B object.

class A: public Derived {
  public:
    A(name N) { ... }
    virtual ~A() {}
}

class B: public Derived {
  public: 
    B(name N) { ... }
    virtual ~B() {}
    A& connect(A &a)
    {
      // do something else
    }
}

int main(int argc, char *argv[])
{
  A objA("A");
  B objB("B");

  // Here's where is my issue
  objB.connect(objA);
}

When I call objB.connect(objA), it is actually calling Base& connect(Base &b). I understand because both are child of Base and both have connect() defined in Derived. But the thing is that I would like that whenever I have objB.connect(objA), it should call A& connect(A &a) instead.

I would like to know if there is a way to have it the way I want.

Thanks :)

UPDATE

I edited this, because I had several typos. I didn't copy-paste the code, because it is quite more complex than I wish >.< Hope it is enough.

Foi útil?

Solução

Your code won't compile. Here is code that compiles and result is as you desire: you can choose which version of connect to call based on a pointer type:

class Base {
  public:
    virtual ~Base() {}
    virtual Base& connect(Base &b) = 0;
};

class Derived: public Base {
  public:
    virtual ~Derived() {}
    virtual Base& connect(Base &b)
    {
      qDebug() << "Baseconnect";
    }
};

class AA: public Derived {
  public:
    AA() {}
    virtual ~AA() {}
};

class BB: public Derived {
  public:
    BB() {}
    virtual ~BB() {}
    AA& connect(AA &a)
    {
        qDebug() << "Aconnect";
    }
};

example:

int main(int argc, char *argv[])
{
    AA* aaptr = new AA;
    BB* bbptr = new BB;
    bbptr->connect(*aaptr);  // version from BB is called
    Derived* dptr = new BB;
    dptr->connect(*aaptr);   // version from Derived is called
    // ...
}

As a side note, please always ensure that your code compiles and question is well defined. You narrow down the chances for helpful answer to your question otherwise.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top