我正在嘗試編寫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;
}
'name = new string [name];'這是應該做什麼的?你根本不需要分配srring的堆,使用'string name;'。你不需要複製構造函數或析構函數。 –