본문 바로가기
언어 공부/C++

연산자 오버로딩

by 세희홍 2022. 7. 4.

클래스 간의 연산을 사용자가 원하는 형태로 정의해서 사용할 수 있다. 

#include <iostream>
#include <string>
using namespace std;

class Complex {
private:
	int real; // 실수부
	int imaginary; // 허수부
public:
	Complex(int real, int imaginary) : real(real), imaginary(imaginary) {}
	int Real(int real) {
		this->real = real;
		return real;
	}
	int Imaginary(int imaginary) {
		this->imaginary = imaginary;
		return imaginary;
	}
	int Real() const { return real; }// constant 오버로딩
	int Imaginary() const { return imaginary; }

};

int main() {
	Complex c1(13, 7);
	Complex c2(2, 9);
	Complex c3(0, 0);
	c3 = c1 + c2; //에러/ 어떻게 더하기를 할지 정의가 안됨
	cout << c3.Real() << "+" << c3.Imaginary() << "i\n";
}

Complex 클래스를 정의하여 실수부인 real끼리, 허수부인 imaginary끼리 연산을 하려고 한다. 

c3 = c1 + c2;에서 에러가 발생하는데, 이는 클래스간의 + 연산에 대한 정의가 없기 때문에 발생한 것이다.

 

	Complex operator+(const Complex& rhs) { //rhs는 c2
		int r = this->real + rhs.real;
		int i = this->imaginary + rhs.imaginary;
		return Complex(r, i);
	}

Complex 클래스 안에 +에 대한 연산자 오버로딩을 해주면 '15+16i'로 출력이 된다.

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

둘의 결과는 같다. c1이 oprtator+ 실행. 실행시점의 객체인 this는 c1이다. 매개변수로 c2가 전달이 되서 연산이 된다. 


전치연산 & 후위연산

	Complex operator++() { // 전치연산
		this->real++;
		return *this;
	}
	Complex operator++(int) { // 후위연산
		Complex prev(this->real, this->imaginary);//현재 상태를 가진 객체
		this->real++;
		return prev;// 더하기 전의 객체를 리턴
	}

전치연산과 후위연산은 매개변수의 유뮤로 구분한다. 

전치연산: 후위연산을 한 후, 객체의 주소를 리턴한다.

후위연산: 현재 상태를 가진 객체 prev를 선언. 더하기 전의 객체를 리턴.

 


입출력

cout << postfix; // 에러

내가 만든 복소수 객체를 표준입출력으로 출력불가. 출력객체 연산자오버로딩 해야한다.

	friend ostream& operator<<(ostream& of, const Complex& rhs) { 
		cout << rhs.Real() << "+" << rhs.Imaginary() << "i\n";
		return of;
	}

출력연산자를 선언해서 출력한다.


일반함수

Complex operator+(const Complex& lhs, const Complex& rhs) { //rhs는 c2
	int r = lhs.real + rhs.real; //일반함수. private이라 접근이 안됨
	int i = lhs.imaginary + rhs.imaginary;
	return Complex(r, i);
}

클래스 외부에서 일반함수를 정의하는 경우, this로는 접근이 되지 않으니까 객체 이름으로 접근한다. 

'언어 공부 > C++' 카테고리의 다른 글

예외 처리2  (0) 2022.07.06
예외 처리  (0) 2022.07.06
다중 상속  (0) 2022.07.04
추상클래스  (0) 2022.07.04
열거체(enumeration)  (0) 2022.06.29

댓글