#include <iostream>
namespace myStd
{
using namespace std; // myStd 내에서만 사용
class ostream {
public :
ostream& operator<<(const char * str) {
printf("%s", str);
return *this;
}
ostream& operator<<(char ch) {
printf("%c", ch);
return *this;
}
ostream& operator<<(int num) {
printf("%d", num);
return *this;
}
ostream& operator<<(double e) {
printf("%g", e);
return *this;
}
ostream& operator<<(ostream& (*fp)(ostream&)) {
return fp(*this);
}
};
ostream& endl(ostream& os) { // 전역함수
os << '\n';
fflush(stdout); // 출력버퍼 비우기
return os;
}
ostream cout; // 객체 생성
}
int main() {
using myStd::cout;
using myStd::endl;
cout << "파이는 " << 3.14 << " " << 123 << endl;
return 0;
}
예제에서 보이듯이 셀프레퍼런스를 반환하여 계속 사용이 가능하게 구성되었다.
Point pos(10,20);
cout << pos << endl;
#include <iostream>
using namespace std;
class Point {
int xPos;
int yPos;
public:
Point() {}
Point(int x, int y)
: xPos(x), yPos(y) {}
friend ostream& operator<<(ostream& os, const Point& ref);
};
ostream& operator<<(ostream& os, const Point& ref) {
os << "[" << ref.xPos << ", " << ref.yPos << "]";
return os;
}
int main() {
Point pos(10, 20);
cout << pos << endl;
return 0;
}
#include <iostream>
using namespace std;
class Point {
int xPos;
int yPos;
public:
Point() {}
Point(int x, int y)
: xPos(x), yPos(y) {}
friend ostream& operator<<(ostream& os, const Point& ref);
friend istream& operator>>(istream& is, Point& ref);
};
ostream& operator<<(ostream& os, const Point& ref) {
os << "[" << ref.xPos << ", " << ref.yPos << "]";
return os;
}
istream& operator>>(istream& is, Point& ref) {
is >> ref.xPos >> ref.yPos;
return is;
}
int main() {
Point pos;
cout << "x, y 형태로 입력 : ";
cin >> pos;
cout << pos << endl;
return 0;
}