객체 지향 원리를 이해하기 위한 Absolute C++ 8장 실습

1. 모든 기본 연산자는 기본적으로 기본 데이터 유형에 정의됩니다.

사용자 정의 데이터 유형에는 사용할 수 없습니다.

따라서 파생 데이터 형식에서 작동하려면 기본 연산자를 오버로드해야 합니다.

(ex. 객체)

2.

class Money 연산자 > (const Money& amount1, const Money& amount) {
int 달러1 = amount1.getDollars();
int dollar2 = amount2.getDollars();
int cents1 = amount1.getCents();
int cents2 = amount2.getCents();

return ((달러1 > 달러2) || ((달러1 == 달러2) && (센트1 > 센트2)));
}

삼.

다음 연산자는 오버로드할 수 없습니다.

(도트 연산자, ::, sizeof, ?:, ->, *)

또한 오버로딩 시 적어도 하나의 피연산자는 클래스 타입이어야 합니다.

4. 적합합니다.

6. 클래스의 멤버 함수는 아니지만 클래스의 전용 멤버에 액세스할 수 있으며 모든 인수에 대해 자동 유형 변환을 지원합니다.

7.

클래스 화폐 연산자 – (const Money& amount1, Money& amount2) {
int allCents1 = amount1.dollars * 100 + amount1.cents;
int allCents2 = amount2.dollars * 100 + amount2.cents;
int difAllCents = allCents1 – allCents2;
int absAllCents = abs(difAllCents);
int finalDollars = absAllCents / 100;
int finalCents = absAllCents % 100;

return Money(finalDollars, finalCents);
}

8.

클래스 통화 연산자 > (const Money& amount1, Money& amount2) {
int 달러1 = 금액1.달러;
int dollar2 = amount2.dollars;
int cents1 = amount1.cents;
int cents2 = amount2.cents;

return ((달러1 > 달러2) || ((달러1 == 달러2) && (센트1 > 센트2)));
}

11.

istream& 연산자 >> (istream& inputStream, Percent& aPercent) {
inputStream >> aPercent.value;
반환 입력 스트림;
}

ostream& 연산자 << (ostream& outputStream, const Percent& aPercent) {
outputStream << aPercent.value;
반환 outputStream;
}