728x90
반응형
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | #include <iostream> #define _CRT_SECURE_NO_WARNINGS #pragma warning(disable:4996) #include <string> using namespace std; struct Point { //변수의 크기가 작거나 자주할당되는 객체는 구조체가 좋음 int x, y; }; class Polygon { private: int nPoints; Point* points; public: Polygon() { nPoints = 0; points = NULL; } Polygon(const int nPoints, const Point* points) :nPoints(nPoints) { this->points = new Point[nPoints]; for (int i = 0; i < nPoints; i++) { this->points[i] = points[i]; } } //복사 생성자 Polygon(const Polygon& rhs) { nPoints = rhs.nPoints; points = new Point[nPoints]; for (int i = 0; i < nPoints; i++) { points[i] = rhs.points[i]; //points는 구조체임 //구조체 내의 x,y는 포인터가 아니여서 깊은복사됨 } cout << "깊은복사" << endl; } //이동 생성자 Polygon(Polygon&& rhs) { nPoints = rhs.nPoints; points = rhs.points; //원본객체가 가리키는거 끊어줘야 rhs.points = NULL; cout << "얕은복사" << endl; } ~Polygon() { delete[] points; } //복사 대입연산자 Polygon& operator=(const Polygon& rhs) { if (this != &rhs) { delete[]points; // points에할당되어 있는거 미리 제거해줘야함. nPoints = rhs.nPoints; points = new Point[nPoints+ 1]; for (int i = 0; i < nPoints; i++) { points[i] = rhs.points[i]; } } cout << "깊은복사" << endl; return *this; } //이동 대입연산자 구현 Polygon &operator=(Polygon&& rhs) { //자기 자신 대입하는거 막기 위함. if (this != &rhs) { nPoints = rhs.nPoints; delete[] points; //자기 자신 대입한거 있다면 버리고 points = rhs.points;//얕은복사 rhs.points = NULL;//얕은복사하는 대신 연결을 끊어주기 cout << "얕은복사" << endl; return *this; } } int getNPoints() const { return nPoints; } Point* getPoints() const { if (nPoints == 0) { return NULL; } return points; } }; Polygon getSquare() { Point points[4] = { {0,0},{1,0},{1,1},{0,1} }; Polygon p(4, points); return p; } int main() { Polygon a; a = getSquare();//얕은 복사 2회 Polygon b = a;//깊은 복사 1회 Polygon c; c = a;//깊은복사 1회 int nPoints = c.getNPoints(); Point* points = c.getPoints(); for (int i = 0; i < nPoints; i++) { cout << "(" << points[i].x << "," << points[i].y << ")" << endl; } } | cs |
728x90
반응형
'C++ > 기초(두들낙서)' 카테고리의 다른 글
[C++] 순수가상함수와 추상클래스 (0) | 2022.07.12 |
---|---|
[C++] 오버라이딩과 정적바인딩 / 가상함수와 동적바인딩 (0) | 2022.07.10 |
[C++] 묵시적 형변환 (0) | 2022.07.10 |
[C++] 이동 시맨틱 (0) | 2022.07.10 |
[C++] 분할 컴파일/ (0) | 2022.07.05 |
댓글