派生类参数重载;调用w基类param [英] Overload by deriv class param; call w base class param
问题描述
抽象基类A.从A派生的是B类和C类,都是具体的。
我持有指向A类对象的指针,一个实例是B
或C.
我在完成以下工作时遇到问题,而我认为应该可以实现
:
A * pA =新B; //其中一个......
A * pA =新C; // ...这两个
DoSomething(pA); //调用重载方法
这个被调用的方法重载了,看起来像这样:
void DoSomething(B * pB)
{
//代码处理B
}
无效DoSomething(C * pC)
{
//处理C的代码)
}
如果不可能, 我该怎么办?以下是唯一的
方式吗?
无效DoSomething(A * pA)
{
if(pA-> IsTypeOf(B))
//代码处理B
else if(pA-> IsTypeOf(C))
//处理C的代码
}
必须有更多的OO。
>
谢谢,
E.
Abstract base class A. Derived from A are class B and C, both concrete.
I hold a pointer to an object of class A, an instance which is either B
or C.
I have trouble with making the following work, while I think it should
be possible:
A *pA = new B; // One of...
A *pA = new C; // ...these two
DoSomething(pA); // Call overloaded method
This called method is overloaded, and looks like this:
void DoSomething(B *pB)
{
// Code to handle a B
}
void DoSomething(C *pC)
{
// Code to handle a C)
}
If this is not possible, what should I do? Is the following the only
way?
void DoSomething(A *pA)
{
if (pA->IsTypeOf(B))
// Code to handle a B
else if (pA->IsTypeOf(C))
// Code to handle a C
}
There must be something more "OO".
Thanks,
E.
推荐答案
* ectoplasm:
* ectoplasm:
使DoSomething成为A类的虚拟成员函数。
-
答:因为它弄乱了人们通常阅读文字的顺序。
问:为什么这么糟糕?
A:热门发布。
问:usenet和电子邮件中最烦人的事情是什么?
Make DoSomething a virtual member function of class A.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Alf P. Steinbach,谢谢。但是我的例子简化了一些事情,我忘了提到:b
我想要实现的方法不应该是(虚拟的)
A.的成员是否有其他解决方案?
Alf P. Steinbach, thanks. But my example simplified things and I forgot
to mention: the methods I want to implement shall not be (virtual)
members of A. Are there other solutions?
* ectoplasm:
* ectoplasm:
Alf P. Steinbach,谢谢。但是我的例子简化了一些事情,我忘了提到:我想要实现的方法不应该是(虚拟的)A的成员。还有其他解决方案吗?
Alf P. Steinbach, thanks. But my example simplified things and I forgot
to mention: the methods I want to implement shall not be (virtual)
members of A. Are there other solutions?
取决于问题所在。
-
答:因为它弄乱了人们通常阅读文本的顺序。
问:为什么这么糟糕?
A:热门发布。
问:usenet上最烦人的事情是什么?在电子邮件中?
Depends what the problem is.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
这篇关于派生类参数重载;调用w基类param的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!