본문 바로가기
프로그래밍 언어/C++

[C++] 대입 연산자 재정의 (Assignment Operator)

by 까망 하르방 2025. 3. 7.
반응형

대입 연산자

• 사용자가 만들지 않으면 컴파일러가 기본 구현 제공

 (모든 멤버 복사)

• 멤버 함수로만 만들 수 있다.

 

[예제]
복사 생성자: 객체 생성할 때 초기화 하는 것
대입 연산자: 객체를 생성 후에 값을 넣는 것

class Point
{
public:
	int x = 0;
	int y = 0;

	Point() = default;
	Point(int x, int y) : x{ x }, y{ y } {}
};

int main()
{
	Point p1 { 1, 1 };
	Point p2;

	Point p3 = p1; // 복사 생성자

	p2 = p1; // 대입 연산자 p2.operator=(p1)
}



[예제] 대입 연산자

#include <print>

class Point
{
public:
	int x{ 0 };
	int y{ 0 };

	Point() = default;
	Point(int x, int y) : x{ x }, y{ y } {}

	Point& operator=(const Point& other)
	{
		if (&other == this) return *this;

		x = other.x;
		y = other.y;

		return *this;
	}
};

int main()
{
	Point p1{ 1,2 };
	Point p2;

	p2 = p1; // p2.operator=(p1)
	p2 = p2; // 자기 자신 대입
}

 

• 자기 자신을 대입하는 경우를 대비한다.
• 일반적으로 자신을 참조 반환하도록 구현
• Point& operator=(const Point& other) 결과가 달라지므로
 → Point& operator=(const Point& other) const 가 될 수 없다.

 

📌 [C++] 상수 멤버함수 const member function

 

[C++] 상수 멤버함수 const member function

상수 멤버 함수 (const member function)• 컴파일러에게 상수 멤버 함수인 것을 알게 해주는 것• 멤버 함수의 괄호() 뒤쪽에 const 키워드 사용 함수 선언과 구현으로 분리하는 경우 양쪽에 모두 붙인

zoosso.tistory.com


Q) 컴파일러가 기본적으로 제공하는데 굳이 사용자가 구현 필요한가?
A) 일반적인 클래스라면 컴팡일러 제공버전도 상관 없지만
  클래스 안에 포인터 멤버 등이 있으면 주의 필요

 


Q) 컴팡이러가 대입 연산자를 만들지 못하게 하려면?
A) 함수 삭제(= delete) 문법 사용

 

[예제] 함수 삭제 (= delete)

class Point
{
public:
	int x{ 0 };
	int y{ 0 };

	Point() = default;
	Point(int x, int y) : x{ x }, y{ y } {}

	Point& operator=(const Point&) = delete;
};

int main()
{
	Point p1{ 1,2 };
	Point p2;

	p2 = p1; // error
}

 

 

📌 [C++] 연산자 재정의 (Operator Overloading)

 

[C++] 연산자 재정의 (Operator Overloading)

연산자 재정의 (Operator Overloading)사용자 정의 타입에서 +, - 등 연산자 사용할 수 있는 문법class Point{ int x = 0; int y = 0;public: Point() = default; Point(int x, int y) : x{ x }, y{ y } {}};int main(){ Point p1{ 1, 1 }; Point

zoosso.tistory.com

 

반응형

댓글