operator<는 피연산자의 부피를 비교하고, operator==()는 데이터 멤버의 값을 비교한다. Box 객체에 대한 operator>>와 operator<<도 Box.h에 inline으로 오버로딩을 정의할 수 있다.
// operator>> 연산자(스트림 추출) inline std::istream& operator>>(std::istream& in, Box& box) { return box.read(in); } // operator<< 연산자(스트림 삽입) inline std::ostream& operator<<(std::ostream& out, Box& box) { return box.write(out); }
operator>>와 operator<< 함수는 각각 연산을 수행하기에 적합한 함수 멤버, 여기서는 read()와 write()를 호출한다. 함수 객체가 virtual로 선언되어 있으니 파생 클래스에서 이들 함수를 재정의해두면 연산자 함수 호출에 따라 두 번째 인수로 전달된 객체 타입에 해당하는 read()나 write() 함수를 호출하게 된다.
Box.h의 전체 코드는 다음과 같다.
// Box.h // Carton 클래스의 기반이 될 Box 클래스 정의 #ifndef BOX_H #define BOX_H #include <iostream> // 표준 스트림 #include <istream> // 스트림 클래스 #include <utility> // 비교 연산자 템플릿 using namespace std::rel_ops; // 비교 연산자 템플릿 네임스페이스