tailieunhanh - Thinking in C plus plus (P21)
Tham khảo tài liệu 'thinking in c plus plus (p21)', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | str s 0 width friend ostream operator ostream os Fixw fw return os typedef unsigned long ulong Print a number in binary class Bin ulong n public Bin ulong nn n nn friend ostream operator ostream Bin ostream operator ostream os Bin b ulong bit ULONG_MAX 1 Top bit set while bit os bit 1 0 bit 1 return os int main char string Things that make us happy make us wise for int i 1 i strlen string i cout Fixw string i endl ulong x OxCAFEBABEUL ulong y 0x76543210UL cout x in binary Bin x endl cout y in binary Bin y endl The constructor for Fixw creates a shortened copy of its char argument and the destructor releases the memory created for this copy. The overloaded operator takes the contents of its second argument the Fixw object and inserts it into the first argument the ostream then returns the ostream so it can be used in a chained expression. When you use Fixw in an expression like this cout Fixw string i endl Chapter 14 Templates Container Classes 101 a temporary object is created by the call to the Fixw constructor and that temporary is passed to operator . The effect is that of a manipulator with arguments. The Bin effector relies on the fact that shifting an unsigned number to the right shifts zeros into the high bits. ULONG_MAX the largest unsigned long value from the standard include file climits is used to produce a value with the high bit set and this value is moved across the number in question by shifting it masking each bit. Initially the problem with this technique was that once you created a class called Fixw for char or Bin for unsigned long no one else could create a different Fixw or Bin class for their type. However with namespaces covered in Chapter XX this problem is eliminated. lostream examples In this section you ll see some examples of what you can do with all the information you ve learned in this chapter. Although many tools exist to manipulate bytes stream editors like sed and awk from Unix are perhaps the most well known but a text
đang nạp các trang xem trước