[c++] 함수 오버로딩과 열람 연산자
열람 연산자는 C++에서 객체의 출력을 제어하는 방법을 제공합니다. 이 연산자의 오버로딩은 객체를 출력하는 데 사용되며, 클래스의 멤버 변수를 원하는 형식으로 출력할 수 있도록 합니다.
아래는 함수 오버로딩 및 열람 연산자의 간단한 예제입니다.
#include <iostream>
using namespace std;
class Box {
public:
double length;
double breadth;
double height;
};
// 열람 연산자 오버로딩
ostream& operator<<(ostream& os, const Box& box) {
os << "Length: " << box.length << ", Breadth: " << box.breadth << ", Height: " << box.height;
return os;
}
int main() {
Box box1;
box1.length = 5.0;
box1.breadth = 6.0;
box1.height = 7.0;
Box box2;
box2.length = 10.0;
box2.breadth = 12.0;
box2.height = 15.0;
cout << box1 << endl; // 열람 연산자를 통한 출력
cout << box2 << endl; // 열람 연산자를 통한 출력
return 0;
}
이 예제에서는 Box 클래스의 멤버 변수를 출력하기 위해 <<
연산자를 오버로딩합니다. 이후 main 함수에서는 두 개의 Box 객체를 선언하고 열람 연산자를 사용하여 각 객체를 출력합니다.
참고 문헌:
- https://www.learncpp.com/cpp-tutorial/98-overloading-the-io-operators/
- https://www.geeksforgeeks.org/c-run-overloading-of-avert-cout-for-user-defined-classes/