という名前のアドレスを出力するように、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;
}
「名前=新しい文字列[名前];」これは何をする予定ですか?ここでsrringを割り当てたヒープは必要ありません。 'string name;'を使用してください。コピーコンストラクタやデストラクタも必要ありません。 –