2013-06-30 105 views
0

假设我有一个类形状和2个派生类,它们是圆形和方形的。该代码是:C++将指针从一个派生类转换为另一个

Shape* s1 = new circle; 

现在我想asssigne S1方,同时保留两者共同的变量。

Shape* s1 = new Square; 

我该怎么做?

+1

你是什么意思“保留变量”? –

+1

我认为他的意思是“成员”。没有使用转换功能是不可能的。你为什么要把一个圆转换成一个方形? –

+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; 

编辑:这是一个关于拷贝构造函数和assignement运营商链接:http://www.cplusplus.com/articles/y8hv0pDG/

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()); 
} 
相关问题