©2003 Prentice Hall, Inc. All rights reserved.
1
Chapter 8 - Operator Overloading
Outline
8.1 Introduction
8.2 Fundamentals of Operator Overloading
8.3 Restrictions on Operator Overloading
8.4 Operator Functions as Class Members vs. as friend Functions
8.5 Overloading Stream-Insertion and Stream-Extraction Operators
8.6 Overloading Unary Operators
8.7 Overloading Binary Operators
8.8 Case Study: Array Class
8.9 Converting between Types
8.10 Case Study: A String Class
8.11 Overloading ++ and --
8.12 Case Study: A Date Class
8.13 Standard Library Classes string and vector
©2003 Prentice Hall, Inc. All rights reserved.
2
8.1 Introduction
•S dng các toán t vi các đối tượng (operator
overloading)
đối vi mt s lp, s dng toán t trong sáng hơn s dng các li
gi hàm
object2 = object1.add(object2);
object2 = object2 + object1;
toán t cm ng cnh (sensitive to context)
Ví d
<<
chèn vào dòng (Stream insertion), phép dch trái nh phân (bitwise
left-shift)
+
–thc hin tính cng cho nhiu kiu d liu (integers, floats, etc.)
©2003 Prentice Hall, Inc. All rights reserved.
3
8.2 Fundamentals of Operator Overloading
•Các kiu d liu
–Có sn (Built in) (int, char) hoc kiu người dùng (user-
defined)
–Có th s dng các toán t có sn cho các kiu d liu ngưi
dùng
Không th to toán t mi
Overloading operators
–To mt hàm ca lp
Đặt tên hàm là operator tiếp theo là ký hiu
Operator+ dành cho phép cng +
©2003 Prentice Hall, Inc. All rights reserved.
4
8.2 Fundamentals of Operator Overloading
•S dng toán t vi mt đối tưng
–Nó phi được overloaded cho lp đó
ngoi tr:
phép gán, =
phép gán tng thành viên ca đối tượng này cho đối tưng
kia (Memberwise assignment between objects)
toán t địa ch,&
–tr v địa ch ca đối tượng
•c hai đều có th được overloaded
Overloading cho ký hiu ngn gn
object2 = object1.add(object2);
object2 = object2 + object1;
©2003 Prentice Hall, Inc. All rights reserved.
5
8.3 Restrictions on Operator Overloading
Không th thay đổi:
–Hot động ca các toán t đối vi các kiu d liu có sn
•ví d., không th thay đổi phép cng s nguyên
–Th t ưu tiên ca các toán t
Quan h kết hp - Associativity (left-to-right hoc right-to-
left)
–S lượng toán hng (operand)
&là toán t đơn, ch dành cho mt toán hng
Không th to các toán t mi
Các toán t phi được overloaded mt cách tường
minh
–Overload+không có nghĩac += cũng được overload