在c ++中贬低我无法成功 [英] downcasting in c++ I couldnt success
问题描述
A级{
..
};
B级:公众A
{
..
};
int main()
{
stack< Amystack;
A a = new B();
mystack.push(a);
a newA = mystack.top();
B b =(B)newA; //不在这里工作
返回0;
}
怎么能做垂头丧气???
class A {
..
};
class B : public A
{
..
};
int main( )
{
stack<Amystack;
A a = new B( );
mystack.push(a);
A newA = mystack.top( );
B b = (B) newA; //doesnt work here
return 0;
}
how could I do downcast???
推荐答案
eMRe< em ******** @ gmail.comwrites:
eMRe <em********@gmail.comwrites:
class A {
class A {
[snip]
您正在寻找comp.lang.c ++。
-
Keith Thompson(The_Other_Keith) ks *** @ mib.org < http://www.ghoti.net/~kst>
诺基亚
我们必须做点什么。这是事情。因此,我们必须这样做。
- Antony Jay和Jonathan Lynn,是部长
[snip]
You''re looking for comp.lang.c++.
--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
2008年10月4日21:10,eMRe写道:
On 4 Oct 2008 at 21:10, eMRe wrote:
class B:public A
class B : public A
[snip]
[snip]
newA = mystack.top();
B b =(B)newA; //不在这里工作
我怎么能做垂头丧气???
A newA = mystack.top( );
B b = (B) newA; //doesnt work here
how could I do downcast???
由于B是从A派生的,所以从
A转换为B是没有意义的。
如果您碰巧知道您弹出的对象实际上是B,
那么您可以使用dynamic_cast转换(指向对象的指针)。 (如果
演员表无效,那么dynamic_cast将返回NULL。)
Since B is derived from A, in general it doesn''t make sense to cast from
A to B.
If you happen to know that the object you''ve popped is actually a B,
then you can convert (a pointer to the object) with dynamic_cast. (If
the cast isn''t valid, then dynamic_cast will return NULL.)
eMRe写道:
请不要在Usenet上多发帖子。
eMRe wrote:
Please don''t multi-post on Usenet.
>
我怎么办?沮丧???
>
how could I do downcast???
您在相应的小组中得到的答案有什么问题?
-
Ian Collins。
What was wrong with the answer you got in the appropriate group?
--
Ian Collins.
这篇关于在c ++中贬低我无法成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!