2013-06-30 5 views
0

나는 클래스 모양과 2 개의 파생 클래스를 원과 사각형이라고합니다. 코드는 다음과 같습니다.C++ 한 파생 클래스의 포인터를 다른 파생 클래스로 변환

Shape* s1 = new circle; 

이제 저는 두 가지 모두에 공통적 인 변수를 보존하면서 asssigne s1을 사각형으로 만들고 싶습니다.

Shape* s1 = new Square; 

어떻게하면됩니까? 원을 사각형으로 변환하는 것은 조금 이상한 것을 잊지 마세요

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) 
    { 
     ... 
    } 

    ... 
}; 

: 함께

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

:

+1

"변수 보존"이란 무엇을 의미합니까? –

+1

그는 "회원"을 의미한다고 생각합니다. 변환 기능을 사용하지 않으면 불가능합니다. 왜 원을 사각형으로 변환하고 싶습니까? –

+1

** ** 그렇게하지 마십시오. "어떻게"는 무의미합니다. –

답변

1

당신은 당신의 복사 생성자를 사용할 수 있습니다.

구현시 메모리 LEAK이 있습니다. 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()); 
} 
관련 문제