第八章运算符重载( Operator Overloading ) 学****目标: ?了解如何重新定义(重载)运算符以处理新的 ADT ?了解如何将一个类的对象转换为另一个类的对象?了解何时可用重载运算符,何时不可用重载运算符?创建 Array 、 String 和 Data 类,举例说明运算符重载 Introduction ? Use operators with objects (operator overloading) ? Clearer than function calls for certain classes ? Operator sensitive to context Introduction ? Examples ?<< ? Stream insertion, bitwise left-shift ?+ ? Performs arithmetic on multiple types (integers, floats, etc.) 软件工程知识 01:运算符重载提高了 C++ 的可扩展性, 也是 C++ 最吸引人的属性之一。良好编程****惯 01:针对同样的操作,使用重载运算符比使用显示函数调用更能提高程序的可读性。良好编程****惯 02:重载运算符应该模拟其相应的内部对象的功能。例如: +运算符重载后,应该仍然执行加法运算,而不是减法运算。 运算符重载的基础知识(Fundamentals of Operator Overloading) ? Types ? Built in ( int , char) or user-defined ? Can use existing operators with user- defined types ? Cannot create new operators 运算符重载的基础知识(Fundamentals of Operator Overloading) ? Overloading operators ? Create a function for the class ? Name function operator followed by symbol ? Operator+ for the addition operator + 运算符重载的基础知识(Fundamentals of Operator Overloading) ? Using operators on a class object ? It must be overloaded for that class Exceptions: ? Assignment operator, = ? Memberwise assignment between objects ? Address operator, & ? Returns address of object ? Both can be overloaded 运算符重载的基础知识(Fundamentals of Operator Overloading) ? Overloading provides concise (简明的) notation (符号) ? object2 = (object2); ? object2 = object2 + object1; 8. 3 运算符重载的限制条件( Restrictions on Operator Overloading ) ? Cannot change ? How operators act on built-in data types ? ., cannot change integer addition ? Precedence( 优先级) of operator (order of evaluation) ? Use parentheses to force order-of- operations 8. 3 运算符重载的限制条件( Restrictions on Operator Overloading ) ? Cannot change ? Associativity ( 结合律)(left-to-right or right-to- left) ? Number of operands ?& is unitary( 一元的), only acts on one operand
第八章 运算符重载 来自淘豆网www.taodocs.com转载请标明出处.