简体   繁体   English

切片与上传::我的理解是否正确?

[英]Slicing vs Upcasting :: Is my understanding correct?

Let A be the base class and B be it's publicly derived class. 设A是基类,B是公共派生类。

B b;

Slicing: 切片:

A a = b; 

Upcasting: 上溯造型:

A* p = &b; // p is a pointer variable of type A
A& r = b; // r is a reference variable of type A

Is this correct? 这个对吗? Please share similar examples to illustrate the two concepts if possible. 如果可能,请分享类似的例子来说明这两个概念。

Yes! 是!

Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object. 当派生类对象被分配给基类对象时,会发生对象切片 ,派生类对象的其他属性被切除以形成基类对象。

So yes, if you have a base class A 所以是的,如果你有一个基类A.

class A{
  public:
    int x;
    char y;
};

and a class B derived publically from A with some extra data members, 和一个B类从A公开派生,带有一些额外的数据成员,

class B:public A{
  public:
    int z;
};

doing A a = b; A a = b; will slice off 'z'. 将切掉'z'。

Upcasting is conversion of pointer or reference of derived class type to pointer or reference of base class type, going up in the inheritance tree. 向上转换是将派生类类型的指针或引用转换为基类类型的指针或引用,在继承树中上升。

B objB;
A *objA = &objB;

Just to bring more light on this subject, you can convert a base-class pointer(reference) to a derived-class pointer (reference).It is called downcasting (opposite to upcasting). 为了更多地了解这个主题,你可以将基类指针(引用)转换为派生类指针(引用)。它被称为向下转换 (与向上转换相反)。

B *objB = (B *) &A;

But there's no way you can assign a base class object to a derived class object. 但是你无法将基类对象分配给派生类对象。

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM