C++/Overloading
2021. 3. 16. 00:19
산술 연산자 오버로딩 (Arithmetic Operator Overloading)
클래스 안에서 정의해도 되고, 밖에서 정의해도 된다.
예제
오버로딩을 하지 않은 예제
#include <iostream> class Cents { int cents_; public: Cents(const int& cents = 0) { cents_ = cents; } int getCents() const { return cents_; } int& getCents() { return cents_; } }; Cents add(const Cents& c1, const Cents& c2) { return Cents(c1.getCents() + c2.getCents()); } int main() { using namespace std; Cents cents1(6); Cents cents2(8); cout << add(cents1, cents2).getCents() << endl; } /* stdout 14 */
+
연산자 오버로딩을 하면 다음과 같다.#include <iostream> class Cents { int cents_; public: Cents(const int& cents = 0) { cents_ = cents; } int getCents() const { return cents_; } int& getCents() { return cents_; } }; Cents operator + (const Cents& c1, const Cents& c2) { return Cents(c1.getCents() + c2.getCents()); } int main() { using namespace std; Cents cents1(6); Cents cents2(8); cout << (cents1 + cents2 + Cents(6)).getCents() << endl; } /* stdout 20 */
클래스 안에서 정의하면 다음과 같다.
#include <iostream> class Cents { int cents_; public: Cents(const int& cents = 0) { cents_ = cents; } int getCents() const { return cents_; } int& getCents() { return cents_; } Cents operator + (const Cents& c2) { return Cents(cents_ + c2.cents_); } }; int main() { using namespace std; Cents cents1(6); Cents cents2(8); cout << (cents1 + cents2 + Cents(16)).getCents() << endl; } /* stdout 30 */
'C++ > Overloading' 카테고리의 다른 글
C++ 증감 연산자 오버로딩 (Increment and Decrement Operator Overloading) (0) | 2021.03.16 |
---|---|
C++ 비교 연산자 오버로딩 (Comparison Operator Overloading) (0) | 2021.03.16 |
C++ 단항 연산자 오버로딩 (Unary Operator Overloading) (0) | 2021.03.16 |
C++ 입출력 연산자 오버로딩 (I/O Operator Overloading) (0) | 2021.03.16 |
C++ 오버로딩 (Overloading) (0) | 2021.03.16 |