[C++] 깊은복사 생성자 예제코드

홈 > IT > IT정보
IT정보

[C++] 깊은복사 생성자 예제코드

3 Selovic 0 134 0 0
#include <iostream>
#include <string>
#pragma warning(disable:4996) //strcpy 에러방지코드
using namespace std;

class Book {
	char *title;
	int price;
public:
	Book(const char* title, int price) {
		this->price = price;
		int size = strlen(title);
		this->title = new char[size + 1];
		strcpy(this->title, title);
	}
	Book(Book &b) {
		this->price = b.price;
		int size = strlen(b.title);
		this->title = new char[size + 1];
		strcpy(this->title, b.title);
	}
	~Book() { delete[]title; }

	void set(const char* title, int price) {
		this->price = price;
		int size = strlen(title);
		this->title = new char[size + 1];
		strcpy(this->title, title);
	}
	void show() { cout << title << ' ' << price << "원" << endl; }
};

int main() {
	Book cpp("명품 C++", 10000);
	Book java = cpp;
	java.set("명품자바", 12000);
	cpp.show();
	java.show();
}

Category
Facebook Twitter GooglePlus KakaoStory KakaoTalk NaverBand
PlusFriend Chat