C++ 重载子类函数,将子类的实例作为参数,如何使用?
我正在尝试创建如下内容:C++ 重载子类函数,将子类的实例作为参数,如何使用?,c++,pointers,overloading,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
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);
}
}
std::列表项;
...
//项目在这里被A和B的实例填充
...
对于(std::list::iterator it=items.begin();it!=items.end();it++){
对于(std::list::iterator it2=items.begin();it2!=items.end();it2++){
(*it)->剂量测量(**it2);
}
}
当参数为a B但我只有指向基类的指针时,如何使B的函数以有利于基类的方式运行
谢谢,这是我第一次问问题,所以我希望结构正确。您将
a
传递给doSomething()
,因此编译器将调用doSomething(a&)
(要么a::doSomething(a&)
本身,要么通过多态性调用派生的doSomething(a&)
)B
不是覆盖doSomething(A&)
,而是隐藏doSomething(B&)
,它与doSomething(A&)
无关。不能将A
传递到doSomething()
并期望调用doSomething(B&)
。要执行您正在尝试的操作,B
需要覆盖doSomething(A&)
,然后通过dynamic\u cast
使用RTTI查找来检查输入值是否实际上是AB
,例如:
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...
}
B类:公共A类{
公众:
虚空剂量测定法(A&);
};
无效B::doSomething(A&A)
{
B*B=动态_-cast(&a);
如果(b)
{
//为所有B对象执行代码,包括
//B的后代的B部分。。。
}
//可选:如果需要,请调用继承的方法
//要调用所有对象的基本代码。。。
A::剂量测定法(A);
}
这听起来像是一个“双重分派”类型的问题……您可能还需要在void doSomething(&B)前面添加“virtual”;非常感谢。我确实考虑过动态_演员,但我不知道在哪里做演员。我像这样实现了它,现在它按预期工作,再次感谢。
class B : public A {
public:
virtual void doSomething(A&);
};
void B::doSomething(A &a)
{
B *b = dynamic_cast<B*>(&a);
if (b)
{
// perform code for all B objects, including
// the B portion of descendant of B...
}
// optional: call the inherited method if you want
// to invoke the base code for all objects...
A::doSomething(a);
}