开发者

How to define copy constructor and = operator override in class with pointers on class object?

I heard that when there is a pointer in a class, there should always be copy constructor and = operator override 开发者_开发问答in C++. I have searched about it and didn't found the explanation about when the pointer points to the class object.

To illustrate my problem:

class Figure
{
    Figure();
    Figure(const Figure& figure)
    Figure(float density);
    ~Figure();
    virtual float volume()=0;

    Figure *next;

protected:
    float density;
};

class Sphere: public Figure
{
    Sphere();
    Sphere(float r);
    Sphere(float r, float density);
    ~Sphere();
    float volume();

private:
    float r;
};

I tried making a copy constructor for class Figure. I get error on the last line saying "object of abstract class type Figure is not allowed". I don't know what am I doing wrong. And I don't know how to make assignment operator override.

Figure::Figure(const Figure& figure)
{
    this->tip = figure.tip;
    this->density = figure.density;
    if (figure.next)
        next = new Figure(*figure.next);
}


The typical solution for this is to make the needed operation abstract, and support it in subclasses.

class Figure {

  virtual Figure * clone() const = 0;
};


class Sphere : public Figure {

  Figure * clone() const {
    return new Sphere(*this);
  }
};

Then of course implement the Sphere copy constructor properly.


Put the copy constructor in Sphere instead. You are trying to directly create a class of type Figure and this won't work as Figure is abstract.


But according to your code Figure does not have a data member called next, only Sphere does.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜