1. 문제

 

7. 원을 추상화한 Circle 클래스는 간단히 아래와 같다.

 

다음 연산이 가능하도록 연산자를 프렌드 함수로 작성하라.

 

 

2. 결과

 

 

 

3. 코드

 


#include <iostream>
using namespace std;

class Circle {
	int radius;
public : 
	Circle(int radius=0) { this->radius = radius; }
	void show() { cout << "radius = " << radius << " 인 원" << endl; }
	Circle operator ++() {
		radius++;
		return *this;
	}
	Circle operator ++(int n) {
		Circle temp = *this;
		radius++;
		return temp;
	}
};
int main() {
	Circle a(5), b(4);
	++a;
	b = a++;
	a.show();
	b.show();
}
C++

 

4. 설명

 

   "++" 연산자 함수를 구현합니다.

 

"++"연산자는 ++a 와 a++ 처럼 실행 순서가 두 개의 경우가 있는데 이 함수들을 구현하기 위해서는 ++a를 구현하는 함수는 매개변수가 없고, a++를 구현하는 함수는 매개변수가 있도록 구현하면 됩니다.

 

 

++a의 사용하는  "++"는 radius++;를 해준 후 return *this;를 해줍니다.

 

 

a++연산자 함수의서 입력받은 매개변수 n은 사용하지 않으므로 그냥 무시하셔도 됩니다. 

 

-> 현재 객체 *this를 Circle변수에 저장한 후 radius++를 해준 후 ++을 해주기 전 저장했었던 temp를 return 하여서 radius++가 되기 전 객체를 return 합니다.

 

 

 

 

 

1. 문제

 

8. 문제 7번의 Circle 객체에 대해 다음 연산이 가능하도록 연산자를 구현하라.

 

 

2. 결과

 

 

 

3. 코드

 

#include <iostream>
using namespace std;

class Circle {
	int radius;
public : 
	Circle(int radius=0) { this->radius = radius; }
	void show() { cout << "radius = " << radius << " 인 원" << endl; }
	friend Circle operator +(int n, Circle c);
};
Circle operator +(int n, Circle c) {
	Circle temp;
	temp.radius = n + c.radius;
	return temp;
}
int main() {
	Circle a(5), b(4);
	b = 1 + a;
	a.show();
	b.show();
}
C++

 

 

4. 설명

 

 b = 1 + a; 연산이 가능하도록  "+" 연산자 함수를 구현 합니다.

 

 

순서가 1 + a이므로 이 함수는 프렌드 함수로 구현을 해주어야 합니다.

 

-> a + 1 이였다면 멤버 함수로 구현할 수 있습니다

 

Circle 클래스 변수 하나를 선언한 후 Circle 클래스 변수 c의 저장된 radius의 +n을 한 값을 새로 선언한 클래스 변수 radius의 저장해 준 후 return 해줍니다.

 

-> 연산자 함수의 return형은 Circle 입니다.

+ Recent posts