2017-04-06 106 views
-1

我正在嘗試編寫Shape類的拷貝構造函數,以便它打印出名稱爲s2的地址。如何在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

'name = new string [name];'這是應該做什麼的?你根本不需要分配srring的堆,使用'string name;'。你不需要複製構造函數或析構函數。 –

回答

0

正如你所創建的字符串指針成員names1和你它調用拷貝構造函數時只是複製到s2,這只是預期的行爲,它顯示的與s1相同的地址 - 它只是複製指針。

如果您想爲每個形狀創建一個唯一的名稱,只需創建一個靜態方法/自由函數來創建一個新名稱,然後在構造函數和複製構造函數中調用該函數,爲每個新實例指定一個唯一的名稱。

爲了什麼是值得的,在這裏使用new運算符並不常見(您是否來自Java背景?) - 您可能只想使用常規的std::string,在這種情況下,您不必執行內存管理(您的代碼現在基本上有內存泄漏,因爲您不需要撥打delete任何地方以釋放通過new分配的內存)。

PS:剛剛看到您剛編輯並更改您的代碼,而我正在輸入我的答案......我不會追蹤這些變化(請原諒),但我留下我的答案在這裏,它的價值。

0

請問您可以嘗試下面的代碼嗎?

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