개발/C, C++
C++ - 연산자 오버로딩을 이용하여 구조체 출력하기 (cout with overloading)
피로물든딸기
2023. 11. 22. 20:22
반응형
C++에서는 << 연산자를 이용해 다양한 타입을 출력할 수 있다.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a = 1;
float b = 3.14;
string c = "hello";
cout << " a : " << a << endl;
cout << " b : " << b << endl;
cout << " c : " << c << endl;
return 0;
}

임의의 구조체를 정의한 후, 출력하면 아래와 같은 에러가 발생한다.
해당 구조체를 출력하는 방법을 << 연산자가 알지 못하기 때문이다.
struct Point
{
int x;
int y;
};
...
Point p = { 3, 7 };
cout << " p : " << p << endl;

원하는 방법대로 Point 구조체를 출력하기 위해 operator <<를 재정의 (overloading)하자.
std::ostream& operator<<(std::ostream& os, const Point& point)
{
os << "(" << point.x << ", " << point.y << ")";
return os;
}
이제 정상적으로 구조체 Point도 출력이 된다.

전체 코드는 다음과 같다.
#include <iostream>
#include <string>
using namespace std;
struct Point
{
int x;
int y;
};
std::ostream& operator<<(std::ostream& os, const Point& point)
{
os << "(" << point.x << ", " << point.y << ")";
return os;
}
int main()
{
int a = 1;
float b = 3.14;
string c = "hello";
cout << " a : " << a << endl;
cout << " b : " << b << endl;
cout << " c : " << c << endl;
Point p = { 3, 7 };
cout << " p : " << p << endl;
return 0;
}
반응형