重载子类函数,它将子类的实例作为参数,如何使用?

时间:2013-12-06 01:54:50

标签: c++ pointers overloading

我正在尝试创建这样的东西:

class A{
public:
  virtual void doSomething(&A); //Generic to do something with ANY two A's 
};  

class B : public A{
 public:
  void doSomething(&B); //More specific for two B's (subclass of A)
}

main(){
  A* p1 = new B();
  A* p2 = new B();

  //Should this execute B::doSomething(&B)? If not, how can I?
  p1->doSomething(*p2); 
}

我的实际实现类似于

 std::list<A*> items; 
...
 //items gets filled with instances of A and B here
...
 for (std::list<A*>::iterator it = items.begin(); it != items.end(); it++){
  for (std::list<A*>::iterator it2 = items.begin(); it2 != items.end(); it2++){
         (*it)->doSomething(**it2);
      }
 }              

当参数为B但我只有指向基类的指针时,如何让B函数运行以支持基类?

谢谢,这是我第一次提问,所以我希望我的结构正确。

1 个答案:

答案 0 :(得分:0)

您正在将A传递给doSomething(),因此编译器将通过多态性调用doSomething(A&)A::doSomething(A&)本身或派生doSomething(A&) )。 B不是覆盖 doSomething(A&)隐藏doSomething(B&)doSomething(A&)无关。您无法将A传递给doSomething()并期望doSomething(B&)被调用。要执行您尝试的操作,B需要覆盖 doSomething(A&),然后通过dynamic_cast使用RTTI查找来检查输入值是否实际为{{1} 1}}或不,例如:

B

class A {
public:
    virtual void doSomething(A&);
};  

void A::doSomething(A &a)
{
    // perform code for all A objects, including
    // the A portion of descendants of A...
}