대입 vs 복사
2024. 3. 22. 19:41ㆍ프로그래밍/C++
1. 대입 연산자(assignment operator)
#include <iostream>
class MyClass {
private:
int data;
public:
MyClass(int value) : data(value) {}
//대안 연산자 오버로딩
MyClass& operator=(const MyClass& other) {
if(this != &other) {//자기 자신에게 대입되는 확인
this->data = other.data;
}
return *this;
}
void display() {
std::cout << "Data: " << data << std::endl;
}
};
int main() {
MyClass obj1(10);
MyClass obj2(20);
obj1.display(); //Data:10
obj2.display(); //Data:20
//대입 연산자를 사용하여 obj2의 값을 obj1에 할당
obj1 = obj2;
obj1.display(); //Data:20
obj2.display(); //Data:20
return 0;
}


2. 복사 생성자(copy constructor)
같은 클래스의 다른 객체를 인자로 받아 그 객체와 동일한 값을 가진 새로운 객체를 생성한다
#include <iostream>
class MyClass {
private:
int data;
public:
//복사 생성자
MyClass(const MyClass& other) : data(other.data) {}
MyClass(int value) : data(value) {}
void display() {
std::cout << "Data: " << data << std::endl;
}
};
int main() {
MyClass obj1(10);
//복사 생성자를 사용하여 obj1을 복사하여 obj2 생성
MyClass obj2(obj1);
obj1.display(); //Data:10
obj2.display(); //Data:10
return 0;
}

벡터 클래스를 통해 복사 생성자, 대입 연산자의 사용 사례를 살펴봅시다.
#include <iostream>
#include <algorithm>
class Vector {
private:
int* data;
int size;
public:
//생성자
Vector(int size) : size(size) {
data = new int[size];
}
//복사 생성자
Vector(const Vector& other) : size(other.size) {
data = new int[size];
std::copy(other.data, other.data + size, data);
}
//대입 연산자
Vector& operator=(const Vector& other) {
if (this != &other) {
delete[] data; //이전 데이터 삭제
size = other.size;
data = new int[size]
std::copy(other.data, other.data + size, data);
}
return *this
}
//소멸자
~Vector() {
delete[] data;
}
//요소 가져오기
int& operator[](int index) {
return data[index];
}
}
int main()
{
Vector a(5);
Vector b(3);
a=b;
return 0;
}

int main()
{
Vector a(5);
Vector b(a);
return 0;
}

'프로그래밍 > C++' 카테고리의 다른 글
임시 객체와 이동 시맨틱 (1) | 2024.03.26 |
---|---|
묵시적 변환 - 변환 생성자(Conversion Constructor) (0) | 2024.03.25 |
Pass by value VS Pass by reference (0) | 2024.03.21 |
대입 연산자 (0) | 2024.03.21 |
깊은 복사(Deep Copy)와 얕은 복사(Shallow Copy) (0) | 2024.03.20 |