미누에요
[C++] 윤성우의 열혈 C++ 10-3 입력을 위한 >> 연산자의 오버로딩 문제풀이 본문
728x90
반응형
SMALL
예제 PointConsoleOutput.cpp 에서 정의한 Point 클래스를 대상으로 아래의 main 함수가 보이는대로 데이터의 입력이 가능하도록, 그리고 실행의 예에서 보이는 대로 출력이 이루어지도록 >> 연산자를 오버로딩 하자.
PointConsoleOutput.cpp
#include <iostream>
using namespace std;
class Point
{
private:
int xpos, ypos;
public:
Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
void ShowPosition() const
{
cout << "[" << xpos << ", " << ypos << "]" << endl;
}
friend ostream &operator<<(ostream &, const Point &);
};
ostream &operator<<(ostream &os, const Point &pos)
{
os << "[" << pos.xpos << ", " << pos.ypos << "]" << endl;
return os;
}
int main(void)
{
Point pos1(1, 3);
cout << pos1;
Point pos2(101, 303);
cout << pos2;
return 0;
}
[main 함수]
int main(void)
{
Point pos1;
cout << "x, y 좌표 순으로 입력 : ";
cin >> pos1;
cout << pos1;
Point pos2;
cout << "x, y 좌표 순으로 입력 : ";
cin >> pos2;
cout << pos2;
return 0;
}
정답
소스코드
#include <iostream>
using namespace std;
class Point
{
private:
int xpos, ypos;
public:
Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
void ShowPosition() const
{
cout << "[" << xpos << ", " << ypos << "]" << endl;
}
friend ostream &operator<<(ostream &, const Point &);
friend istream &operator>>(istream &, Point &);
};
ostream &operator<<(ostream &os, const Point &pos)
{
os << "[" << pos.xpos << ", " << pos.ypos << "]" << endl;
return os;
}
istream &operator>>(istream &is, Point &pos)
{
is >> pos.xpos >> pos.ypos;
return is;
}
int main(void)
{
Point pos1;
cout << "x, y 좌표 순으로 입력 : ";
cin >> pos1;
cout << pos1;
Point pos2;
cout << "x, y 좌표 순으로 입력 : ";
cin >> pos2;
cout << pos2;
return 0;
}
실행 결과
728x90
반응형
LIST
'C++' 카테고리의 다른 글
[C++] 윤성우의 열혈 C++ 11-2 C++ 기반의 데이터 입출력 문제풀이 (1) | 2024.05.21 |
---|---|
[C++] 윤성우의 열혈 C++ 11-1 깊은 복사를 하는 대입 연산자의 정의 문제풀이 (1) | 2024.05.16 |
[C++] 윤성우의 열혈 C++ 10-2 단항 연산자 오버로딩 문제풀이 (0) | 2024.05.12 |
[C++] 윤성우의 열혈 C++ 10-1 두 가지 방법의 연산자 오버로딩 문제풀이 (0) | 2024.05.11 |
[C++] 윤성우의 열혈 C++ 08-1 상속 관계의 확장과 추상 클래스 문제풀이 (0) | 2024.05.03 |