简体   繁体   English

C ++:继承优先级

[英]C++: Inheritance priority

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) . 当我调用objB.connect(objA) ,它实际上是在调用Base& connect(Base &b) I understand because both are child of Base and both have connect() defined in Derived . 我了解是因为它们都是Base子级,并且都具有Derived定义的connect() But the thing is that I would like that whenever I have objB.connect(objA) , it should call A& connect(A &a) instead. 但是问题是,我希望每当我有objB.connect(objA) ,它都应该objB.connect(objA)调用A& connect(A &a)

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. 我没有复制粘贴代码,因为它比我希望的要复杂得多。<希望它就足够了。

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: 这是可编译的代码,结果如您所愿:您可以根据指针类型选择要调用的connect版本:

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. 否则,您会缩小对问题进行有帮助的回答的机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM