自认为对C++比较熟悉,突然看到一些奇怪的代码(在看网上下载的代码Sockets):
class SocketAddress { public: virtual ~SocketAddress() {} /** Get a pointer to the address struct. */ virtual operator struct sockaddr *() = 0; /** Get length of address struct. */ virtual operator socklen_t() = 0; /** Compare two addresses. */ virtual bool operator==(SocketAddress&) = 0; /** Set port number. param port Port number in host byte order */ virtual void SetPort(port_t port) = 0; /** Get port number. eturn Port number in host byte order. */ virtual port_t GetPort() = 0; /** Set socket address. param sa Pointer to either 'struct sockaddr_in' or 'struct sockaddr_in6'. */ virtual void SetAddress(struct sockaddr *sa) = 0; /** Convert address to text. */ virtual std::string Convert(bool include_port) = 0; /** Reverse lookup of address. */ virtual std::string Reverse() = 0; /** Get address family. */ virtual int GetFamily() = 0; /** Address structure is valid. */ virtual bool IsValid() = 0; /** Get a copy of this SocketAddress object. */ virtual std::auto_ptr<SocketAddress> GetCopy() = 0; };
奇怪的代码:
/** Get a pointer to the address struct. */ virtual operator struct sockaddr *() = 0; /** Get length of address struct. */ virtual operator socklen_t() = 0;
最后搜了一下,才知道是对 类型转换 的重载!
socklen_t 是 int 类型 ;
声明:operator XX(); 无返回值,XX就是某个类型;
用法:XX a = (XX)obj; 假设上边SocketAddress非abstract类,例如:SocketAddress sa; int a = (socklen_t)sa; 也就是此时会调用原成员函数operator XX(); 一般返回XX类型值,可以理解成类型转换的重载!
另外:我竟不知道一个自定义类的 构造函数可以用作隐形的类型转换,例如:Class A { A(int i) { val = i}; private int val;} , A a = 5; 解:5 首先通过构造函数A(int)隐形的转换为A类型,然后调用默认的operator=赋值函数,赋值给a;