0

クラス shape と 2 つの派生クラス circle と square があるとします。コードは次のとおりです。

Shape* s1 = new circle;

ここで、両方に共通する変数を保持しながら、s1 を正方形に割り当てたいと思います。

Shape* s1 = new Square;

どうすればいいですか?

4

2 に答える 2

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 に答える