使用派生类的Ptr指向基类,反之亦然 [英] Using Ptr of derived class to point to base class and viceversa

查看:79
本文介绍了使用派生类的Ptr指向基类,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用派生类的Ptr指向基类,反之亦然

类基础

{

....

}

等级派生:公共基础

{

....

}


我想知道使用它时的任何实际情况

a。 B b;

D * p =& b;


b。 B * b;

D d;

b =& d;


任何人都可以解释一下吗?我知道它是理论上OK.But我不能

为什么要这样做?


先谢谢,

Bhanu

Using Ptr of derived class to point to base class and viceversa
class base
{
....
}
class derived : public base
{
....
}

I want to know any practical scenario when this is used
a. B b;
D *p = &b;

b. B *b;
D d;
b = &d;

Can any one explain it?I know it is theoritically OK.But i am not able
why to do such things?

Thanks in Advance,
Bhanu

推荐答案



Bhan写道:

Bhan wrote:
使用派生类的Ptr指向基数上课和副课
班级基地
{
...
}类来源:公共基地
{
... }

我想知道使用它时的任何实际情况
a。 B b;
D * p =& b;

b。 B * b;
D d;
b =& d;

任何人都可以解释一下吗?我知道这是理论上的好。但我不能为什么要做这样的事情?


不会导致切片问题吗?

提前致谢,
Bhanu
Using Ptr of derived class to point to base class and viceversa
class base
{
...
}
class derived : public base
{
...
}

I want to know any practical scenario when this is used
a. B b;
D *p = &b;

b. B *b;
D d;
b = &d;

Can any one explain it?I know it is theoritically OK.But i am not able
why to do such things?
doesnt this lead to the Slicing Problem ?

Thanks in Advance,
Bhanu






placid写道:
Bhan写道:
Bhan wrote:
使用派生类的Ptr指向基类,反之亦然/>班级基础
{
...
}
班级派生:公共基地
{
...
} >
我想知道使用它时的任何实际情况
a。 B b;
D * p =& b;


没有实际使用非衍生类型的物体的向下转型。

b。 B * b;
D d;
b =& d;


Upcasting:一直都在发生。

任何人都可以解释一下吗?我知道这是理论上没问题。但我不能
为什么做这些事情?
Using Ptr of derived class to point to base class and viceversa
class base
{
...
}
class derived : public base
{
...
}

I want to know any practical scenario when this is used
a. B b;
D *p = &b;
No practical use of downcasting from an object not of the derived type.

b. B *b;
D d;
b = &d;
Upcasting: Happens all the time.

Can any one explain it?I know it is theoritically OK.But i am not able
why to do such things?



不会导致切片问题吗?


doesnt this lead to the Slicing Problem ?




复制对象时会发生切片。 OP只是将

指针指向该对象。



Slicing happens when you copy the object. The OP is simply taking
pointers to the object.


所以你的意思是通常使用它?
So you mean this is normally used?
Upcasting :一直发生。
Upcasting: Happens all the time.




B b;

D * p =& b;

但是为什么这样做?为什么没有基地本身的ptr?(下)


B b;

B * p =& b;


你能否使用这两个?

B b;

B * p =& b;

D * p =& b;



B b;
D *p = &b;
But why do this ?why not have a ptr to base class itself ?(below)

B b;
B *p = &b;

Can you give the use of these two?
B b;
B *p = &b;
D *p = &b;


这篇关于使用派生类的Ptr指向基类,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆