최초작성 |
2005/08/12 13:18:50 |
Contents
<<, >>, ==, != 등 오버로딩하기
1 #ifndef __IPADDR_H__ 2 #define __IPADDR_H__ 3 #include <vector> 4 #include <string> 5 using namespace std; 6 7 class ip_address 8 { 9 public: 10 ip_address(); 11 explicit ip_address(const ip_address& src); 12 ip_address& operator= (const ip_address& rhs); 13 14 bool equal(const ip_address& other) const; 15 16 bool from_string(const string& s); 17 string to_string(); 18 19 string ip() const { return ip_; } 20 int port() const { return port_; } 21 22 private: 23 string ip_; 24 int port_; 25 }; 26 27 bool operator== (const ip_address& lhs, const ip_address& rhs); 28 bool operator!= (const ip_address& lhs, const ip_address& rhs); 29 30 #endif
1 #include "ipaddr.h" 2 3 4 bool ip_address::equal(const ip_address& other) const 5 { 6 return ip_ == other.ip_ && port_ == other.port_; 7 } 8 9 bool operator== (const ip_address& lhs, const ip_address& rhs) 10 { 11 return lhs.equal(rhs); 12 } 13 14 bool operator!= (const ip_address& lhs, const ip_address& rhs) 15 { 16 return !lhs.equal(rhs); 17 } 18
operator== 를 non-member 로 정의하면 클래스내의 private 멤버에 접근을 못하게 된다. 그럴경우 접근을 대신해주는 public 함수(위의 경우엔 equal) 를 만들어서 그놈들 대신부르면 된다.
