C ++将指针从一个派生类转换为另一个派生类

时间:2013-06-30 15:57:44

标签: c++ inheritance

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

Shape* s1 = new circle;

现在我想将ss设为正方形,同时保留两者共有的变量。

Shape* s1 = new Square;

我该怎么做?

2 个答案:

答案 0 :(得分: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());
}

答案 1 :(得分: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/

相关问题