0

假设我有一个类形状和 2 个派生类圆形和方形。代码是:

Shape* s1 = new circle;

现在我想将 s1 分配给 square,同时保留两者共有的变量。

Shape* s1 = new Square;

我该怎么做呢?

4

2 回答 2

2

通过使用引用基类的构造函数,您可以轻松地复制公共Shape数据:

#include <assert.h>

enum class Color { red, green, blue };

class Shape {
  public:
    Shape() : color(red) { }
    void setColor(Color new_color) { color = new_color; }
    Color getColor() const { return color; }
  private:
    Color color;
};

class Square : public Shape {
  public:
    Square() { }
    // Using explicit constructor to help avoid accidentally
    // using the wrong type of shape.
    explicit Square(const Shape &that) : Shape(that) { }
};

class Circle : public Shape {
  public:
    Circle() { }
    explicit Circle(const Shape &that) : Shape(that) { }
};

int main(int,char**)
{
  Circle circle;
  circle.setColor(Color::blue);
  Square square(circle);
  assert(circle.getColor()==square.getColor());
}
于 2013-06-30T16:18:20.980 回答
1

您可以使用您的复制构造函数:

Shape* s1 = new Circle;
Shape* s1 = new Square( s1 );

和 :

class Square : public Shape
{
    ...
public:
    Square( const Circle& rhs )
    {
        // Copy the value you want to keep
        // Respect the rules of copy constructor implementation
    }
    // Even better :
    Square( const Shape& rhs )
    {
        ...
    }

    ...
};

不要忘记将圆形转换为方形有点奇怪。

您的实现中存在内存泄漏。如果您不想使用您Circle,请删除它。

这会更好:

Shape* s1 = new Circle;
Shape* s2 = new Square( s1 );

delete s1;

编辑:这是关于复制构造函数和赋值运算符的链接:http ://www.cplusplus.com/articles/y8hv0pDG/

于 2013-06-30T16:14:55.387 回答