参考变量可以避免对象切片 [英] object slicing can be avoided by reference variable

查看:60
本文介绍了参考变量可以避免对象切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对象切片

纠正我,如果我错了,我认为避免对象切片的最佳方法是使用 reference 变量对象本身(我的意思是 up-cast 类)。

但我也读过,通过创建基类抽象,我们也避免了对象切片。我同意编译器会在这种情况下生成错误。但这也会限制基类对象的创建。所以请告诉我除了引用或指针对象还有其他方法可以避免对象切片。请考虑到没有类应该是抽象的,复制构造函数(基类)应该是公共的。

还有其他方法吗?

谢谢advance

Object slicing
correct me if i am wrong what is think "the best way to avoid object slicing is to use reference variable instead of object its self (i mean in up-casting of classes).
But i have also read that by making base class abstract we also avoid object slicing. I agree that compiler will generate an error in that case. But that will also restrict the creation of object of base class.So please tell me except reference or pointer object is there any other way to avoid object slicing. And please take in consideration no class should be abstract and copy constructor(base class) should be public.
Is there any other way?
Thanks in advance

推荐答案

答案是肯定的。



您可以添加一个生成副本的虚拟方法对象,并返回基类的指针类型。您必须为每个派生类编写此方法br $> b $ b

The answer is yes.

You can add a virtual method that produces a copy of the object, and returns a pointer type, of the base class. You'll have to write this method for every derived class.

class CBase
{
public:
    virtual CBase * MakeCopy(void) const { return new CBase(*this); }

public:
    CBase() {}
    CBase(const CBase & rhs) {}
    virtual ~CBase()
};

class CDerived : CBase
{
public:
    virtual CBase * MakeCopy(void) const { return (CBase *) new CDerived(*this); }

public:
    CDerived() {}
    CDerived(const CDerived & rhs) : CBase(*(CBase *) this) {}
    virtual ~CDerived()

};





但是你是对的,你可以不按值传递对象到没有切片的派生类型。



But you're right, you can't pass the object by value, to a type it's derived from without slicing.


对象切片是在将派生类对象作为BaseCls类对象传递的值时发生的,基类是复制构造函数被调用。我们知道使用虚函数概念。
Object Slicing is occurred when a derived class object is passed by value as a BaseCls class object, the base class copy constructor is called. We know that using virtual functions concept.


这篇关于参考变量可以避免对象切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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