-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
해결됨
단항 연산자 오버로딩 방법에 대해 질문있습니다.
24.01.28 18:55 작성 조회수 121
1
9.1 산술 연산자 오버로딩하기 강의에서는 연산자 오버로딩을 멤버 함수, friend
함수, 전역 함수로 구현하는 방법을 각각 알아봤었습니다. 그런데 이번 강의의 단항 연산자 오버로딩은 멤버함수로만 구현하고 전역 함수로 구현하는 내용이 없어 스스로 시도해보았습니다.
https://learn.microsoft.com/en-us/cpp/cpp/overloading-unary-operators?view=msvc-170
위 링크의 아래 내용을 참고하여 작성해 보았습니다.
To declare a unary operator function as a nonmember function, use this declaration form:
return-type
operator
op
(
class-type
);
class Cents {
private:
int m_cents;
public:
Cents(int cents) {
m_cents = cents;
}
int getCents() const {
return m_cents;
}
int& getCents() {
return m_cents;
}
friend std::ostream& operator << (std::ostream& out, const Cents& cents) {
out << cents.m_cents;
return out;
}
};
// 비멤버 함수로 오버로딩
Cents operator -(const Cents& cents) {
return Cents(-cents.getCents());
}
int main() {
Cents cents1(6);
cout << cents1 << endl;
cout << -cents1 << endl;
// 6
// -6
return 0;
}
테스트는 잘 되더라구요. 이렇게 하는 것이 맞나요?
답변을 작성해보세요.
2
Soobak
2024.01.28
안녕하세요, 질문&답변 도우미 Soobak 입니다.
네, 잘 구현하셨습니다.
특히, 객체 지향의 은닉성을 잘 유지하는 부분, C++ 연산자 오버로딩의 기본 원칙 등을 잘 이해하고 계신 것 같습니다.
👍
답변 1