2017-04-06 7 views
-1

という名前のアドレスを出力するように、Shapeクラスのコピーコンストラクタを作成しようとしています。ここで作成方法C++でコンストラクタをコピー

私のコードです:

class Shape { 
private: 
    int x; 
    int y; 
    string * name; 

public: 
    //constructor 
    Shape() { 
     cout << "Inside the constructor" << endl; 

    } 

    //Copy constructor 
    Shape(Shape& source) { 
     cout << "Copy constructor called" << endl; 

     name = new string[name]; 

     copy(source.name, source.name, this->getName); 
    } 


    //Destructor 
    ~Shape() {} 

    void setX(int px) { 
     x = px; 
    } 
    void setY(int py) { 
     y = py; 
    } 

    void setName(string * str) { 
     name = str; 
    } 
    string * getName() { 
     return name; 
    } 


int main() 
{ 
    Shape s1; 
    s1.setName(new string("first shape")); 

    Shape s2(s1); 
    cout << s1.getName() << endl; //will display the address of name for s1 
    cout << s2.getName() << endl; //will display the address of name for s2 
    return 0; 
} 
+0

「名前=新しい文字列[名前];」これは何をする予定ですか?ここでsrringを割り当てたヒープは必要ありません。 'string name;'を使用してください。コピーコンストラクタやデストラクタも必要ありません。 –

答えて

0

あなたがs1のために文字列ポインタメンバーnameを作成し、コピーコンストラクタを呼び出すときにあなただけのs2にコピーしているとして、それが表示されるだけで予想される動作ですs1と同じアドレス - 単にポインタをコピーします。

シェイプごとに固有の名前が必要な場合は、新しい名前を作成する静的メソッド/フリー関数を作成し、コンストラクターとコピーコンストラクターの両方で呼び出して、新しいインスタンスごとに一意の名前を付けます。

ここでnew演算子を使用することは実際には一般的ではありません(Javaの背景から来ていますか?)普通のstd::stringを使用したい場合があります。 newによって割り当てられたメモリを解放するためにどこでもdeleteを呼び出さないので、あなた自身のメモリ管理はあなたのコードでは基本的にメモリリークがあります。

PS:答えを入力しているうちにコードを編集して変更したばかりのことを知っています...変更を追跡しません(申し訳ありません)。しかし、 。

0

次のコードを試してください。

//Copy constructor 
    Shape(Shape& source) { 
     cout << "Copy constructor called" << endl; 
     name = new string[name]; 
     *name = *source.name; 
    } 
関連する問題