Copy constructor: deep copying an abstract class

拜拜、爱过 提交于 2020-01-01 08:26:20

问题


Suppose I have the following (simplified case):

class Color;

class IColor
{
public: 
    virtual Color getValue(const float u, const float v) const = 0;
};

class Color : public IColor
{
public:
    float r,g,b;
    Color(float ar, float ag, float ab) : r(ar), g(ag), b(ab) {}
    Color getValue(const float u, const float v) const 
    { 
        return Color(r, g, b)
    }
}

class Material
{
private:
    IColor* _color;
public:
    Material();
    Material(const Material& m);
}

Now, is there any way for me to do a deep copy of the abstract IColor in the copy constructor of Material? That is, I want the values of whatever m._color might be (a Color, a Texture) to be copied, not just the pointer to the IColor.


回答1:


Take a look at the virtual constructor idiom




回答2:


You could add a clone() function to your interface.




回答3:


You'll have to add that code yourself to the Material copy constructor. Then code to free the allocated IColor in your destructor.

You'll also want to add a virtual destructor to IColor.

The only way to do a deep copy automatically would be to store a color directly instead of a pointer to an IColor.




回答4:


Adding a clone() method to color is probably best, but if you don't have that option, another solution would be to use dynamic_cast to cast IColor* to Color*. Then you can invoke the Color copy constructor.



来源:https://stackoverflow.com/questions/1487238/copy-constructor-deep-copying-an-abstract-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!