2학년 객체지향프로그래밍 05주차수업

서지현·2021년 10월 12일

연산자 오버로딩

    1. 오버로딩 작업에 사용할 데이터 유형을 정의하는 클래스 생성
    1. 클래스의 public 영여에 연산자 함수 정의
    1. 연산자 함수는 member 함수 or friend 함수일 수 있다
    1. 연산자 함수 정의
  • ex) int operator==(vector); 또는 friend int operator==(vector,vector);

member 함수의 방법

class complex {
	float x, y;
public:
	complex() { x = y = 0.; }
	complex(float real, float imag) {
		x = real;
		y = imag;
	}
	complex operator+(complex);
	void display() {
		cout << x << " +j" << y << endl;
	}
};
complex complex::operator+(complex c) {
	complex tmp;
	tmp.x = x + c.x;
	tmp.y = y + c.y;
	return tmp;
}
int main() {
	complex c1(2.5, 3.5), c2(1.6, 2.7), c3;
	c3 = c1 + c2;
	c3.display();
	return 0;
}
  • member function 방식은 argument를 1개 필요로 함
  • 연산자 +는 c2가 아니라 왼쪽 피연산자 c1애 의해서 호출됩니다.
  • c2는 함수에 전달되는 인자의 역할을 합니다.
  • c3 = c1.operator+(c2)
complex complex::operator+(complex c) {
	complex tmp;
	tmp.x = x + c.x;
	tmp.y = y + c.y;
	return tmp;
}

이러한 방식 보다는

complex complex::operator+(complex c) {
	return complex((x + c.x), (y + c.y));
}

다음과 같은 방식이 효율적이고 읽기 좋습니다.

  • 임시로 생성한 객체는 return된 이후 영역 밖으로 사라집니다.

friend 키워드를 이용한 방법

  • friend함수와 member함수의 차이점
    • 멤버함수는 friend함수보다 arguments가 1개 작다
    • 피연산자의 형식이 다른경우 멤버함수는 작동하지 않을 수 있다
class complex {
	float x, y;
public:
	complex() { x = y = 0.; }
	complex(float real, float imag) {
		x = real;
		y = imag;
	}
	friend complex operator+(complex, int);
	friend complex operator+(int, complex);
	void display() {
		cout << x << " +j" << y << endl;
	}
};
complex operator+(complex a, int b) {
	return complex((b + a.x), a.y);
}
complex operator+(int b, complex a) {
	return complex((b + a.x), a.y);
}
int main() {
	complex c1(2.5, 3.5), c2;
	c2 = c1 + 1;
	c2.display();
	c2 = 1 + c1;
	c2.display();
	return 0;
}

형변환

    1. basic -> class
  • 생성자 만들기

    1. class -> basic
  • 연산자 함수 만들기

class dst {
	int code;
public:
	void setcode(int a) { code = a; }
	void display() {
		cout << "dst code= " << code
			<< endl;
	}
};
class src {
	int code;
public:
	src(int a) { code = a; }
	void display() {
		cout << "src code= " << code
			<< endl;
	}
	operator int() { return code * code; }
	operator dst() {
		dst d;
		d.setcode(code * code);
		return d;
	}
};
int main() {
	//int to class
	src s = 5;
	s.display();
	//class to int
	int val = s;
	cout << "val=" << val << endl;
	//class to class
	dst d;
	d = s;
	d.display();
	return 0;
}
profile
안녕하세요

0개의 댓글