반응형
문제
원을 추상화한 Circle 클래스는 간단히 아래와 같다.
class Circle {
int radius;
public:
Circle(int radius = 0) { this->radius = radius; }
void show() { cout << "radius = " << radius << " 인 원" << endl; }
};
다음 연산이 가능하도록 연산자를 프렌드 함수로 작성하라
int main()
{
Circle a(5), b(4);
++a;
b = a++;
a.show();
b.show();
}
결과
radius = 7 인 원
radius = 6 인 원
소스코드
#include<iostream>
using namespace std;
class Circle {
int radius;
public:
Circle(int radius = 0) { this->radius = radius; }
void show() { cout << "radius = " << radius << " 인 원" << endl; }
friend void operator++(Circle& a);
friend Circle& operator++(Circle& a, int b);
};
void operator++(Circle& a)
{
++a.radius;
}
Circle& operator++(Circle& a,int b)
{
Circle temp = a;
a.radius++;
return temp;
}
int main()
{
Circle a(5), b(4);
++a;
b = a++;
a.show();
b.show();
}
설명 : 전위, 후위 연산자 모두 참조 매개변수를 사용한다. 전위 연산자인 ++a 의 경우 리턴 값이 필요없으므로 참조매개변수로 a.radius값을 1증가시킨다. 후위 연산자인 경우 매개 변수를 가지도록 선언이 되며, 후위 연산자는 그 줄의 코드가 실행된 후 증가를 시키기 때문에 참조매개변수를 이용해 a.radius의 값은 증가시켜주지만 temp의 이전의 상태를 삽입하여 리턴한다. 이 때 매개변수는 사용되지 않으므로 무시해도 된다. 단지, 전위인지 후위인지 구분하는 매개 변수이다.
오류 또는 수정 사항 궁금한 점 있으시면 댓글로 남겨주세요.
반응형
'명품C++프로그래밍' 카테고리의 다른 글
명품 C++ programming 실습 문제 7장 10번 (0) | 2021.05.21 |
---|---|
명품 C++ Programming 실습문제 7장 9번 (0) | 2021.05.20 |
명품 C++ Programming 실습문제 7장 7번 (0) | 2021.05.20 |
명품 C++ Programming 실습문제 7장 6번 (0) | 2021.05.20 |
명품 C++ Programming 실습문제 7장 5번 (0) | 2021.05.20 |