연산자 오버로딩

Ryan Ham·2024년 5월 28일
0

C++

목록 보기
17/26

연산자 오버로딩도 그냥 함수라고 생각할 것.


+ 연산자 overloading

일반적으로 객체간의 대입 연산자는 구현이 되어있지만 사칙연산에 대한 연산자 정의는 되어 있지 않다. +연산자 overloading은 코드로 어떻게 구현할 수 있는지 알아보자.

#include <iostream>

using namespace std;

class CNumber {

private:
	int x;
	int y;

public:
	// int x,y를 받는 CNumber 생성자
	CNumber(int _x, int _y) : x(_x), y(_y) {
		cout << "기본 생성자 호출!" << endl;
	}

	// +연산 overloading
	CNumber operator+(const CNumber& ref) {
		CNumber c(x + ref.x, y + ref.y);
		return c;
	}

	// private 멤버 출력 함수
	void ShowPrivate() {
		cout << "x와 y의 값은 : " << x << " " << y << endl;
	}

};

int main() {

	CNumber c1(10, 20);
	CNumber c2(30, 40);
	CNumber c3(0,0);

	c3 = c1 + c2;
	c3.ShowPrivate();

}

연산자 overloading도 함수의 overloading과 그 형태가 매우 비슷하다. Key-point는 "operator"는 named keyword로 되어 있어서 반환 타입 뒤에 operator와 해당 연산자를 연달아서 작성하면 된다. 함수 안에서는 c라는 CNumber 타입의 객체를 만든다. 그후, CNumber type의 임시객체를 복사 생성자(c 객체를 parameter로 받는다.)로 생성하고 이를 return 시킨다.


교환법칙이 성립되어야 할때의 연산자 overloading

#include <iostream>
using namespace std;

class Point {
private:
	int xpos, ypos;
public:
	Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
	void ShowPosition() const {
		cout << '[' << xpos << "," << ypos << ']' << endl;
	}
	// Point 객체, *, int-type이 순서대로 연산 할 경우
	Point operator*(int times) {
		Point pos(xpos * times, ypos * times);
		return pos;
	}
	// int-type, *, Point 객체가 순서대로 연산 할 경우
	// 이렇게 멤버 함수가 아니라 전역으로 선언하면 parameter 부분에 인자를 2개 넣어주어야 한다. 
	friend Point operator*(int times, Point& ref);
};

Point operator*(int times, Point& ref) {
	return ref * times;
}

int main() {
	Point pos(1, 2);
	Point cpy;

	cpy = 3 * pos;
	cpy.ShowPosition();

	cpy = 2 * pos * 3;
	cpy.ShowPosition();
}

단항 연산자 overloading

#include <iostream>
using namespace std;

class Person {
private:
	int age;
public:
	Person(int _age) : age(_age) {
		cout << "Default constructor Initialized" << endl;
	}

	Person(const Person& ref) : age(ref.age) {
		cout << "Copy constructor Initialized" << endl;
	}

	~Person() {
		cout << "Destructor initiated" << endl;
	}

	// 전위 증가에 해당하는 연산자 오버로딩
    // 포인트 1. 함수 선언하는 것처럼 parameter를 받는 ()부분과 몸통 부분인 {}가 존재.
    // 포인트 2. 일반적으로 생각하는 ++ 구현은 전위 증가이다
	Person& operator++(){

		++age;
		return *this;
	}
    
    // 후위 증가에 해당하는 연산자 오버로딩
    // 포인트 1. 전위 증가랑 다르게 *this를 리턴하는 게 아닌 새로운 객체를 만들어서 리턴
    // 포인트 2. parameter 부분의 int는 그냥 구분을 위한 표기일 뿐.
    Person& operator++(int){
    	Person person(age);
        age+=1;
        return person;
};

int main() {

	Person p1(20);
	Person p2(30);
	Person p3(p2);

	++p1;
}
profile
🏦KAIST EE | 🏦SNU AI(빅데이터 핀테크 전문가 과정) | 📙CryptoHipsters 저자

0개의 댓글