10.2 const(Constant)Objects and const member functions常量对象 °目的:一些对象要求是可修改的,另一些则 不希望被修改 o const Time noon 12,, 0 ●将变量和对象声明为 const可提高性能 °要求:不允许调用普通成员函数,仅能调用 noon对象的 const member function(常成 员函数) O 2015, SEU. All rights reserved. 6
© 2009, SEU. All rights reserved. © 2015, SEU. All rights reserved. 6 10.2 const (Constant) Objects and const Member Functions—常量对象 目的:一些对象要求是可修改的,另一些则 不希望被修改 const Time noon( 12, 0, 0 ); 将变量和对象声明为const可提高性能 要求:不允许调用普通成员函数,仅能调用 noon对象的const member function (常成 员函数)
10.2 const(Constant)Objects and const Member functions常成员函数 目的:通过把成员函数声明为 const,以表明它们 不修改类的成员变量 常成员函数(两处都要声明) o prototype void printUniversalO const o definition. void Time: printUniversal0 const (. J 要求: °不能修改本对象的数据成员 °不能调用本对象其它non-cons成员函数 O 2015, SEU. All rights reserved. 7
© 2009, SEU. All rights reserved. © 2015, SEU. All rights reserved. 7 10.2 const (Constant) Objects and const Member Functions—常成员函数 目的:通过把成员函数声明为const,以表明它们 不修改类的成员变量 常成员函数(两处都要声明) prototype: void printUniversal() const; definition: void Time::printUniversal() const { … } 要求: 不能修改本对象的数据成员 不能调用本对象其它non-const成员函数
10.2 const(Constant)Objects and const member functions一访问权限 OBJECT Member Function Access const const const non-const non-const const X√√ non-const non-const o 2015, SEU. All rights reserved. 8
© 2009, SEU. All rights reserved. © 2015, SEU. All rights reserved. 8 10.2 const (Constant) Objects and const Member Functions—访问权限 OBJECT Member Function Access const const √ const non-const X non-const const √ non-const non-const √
10.2 const(Constant) Objects and const Member Functions class time public Time (int =0, int =0, int =0 void setTime( int, int, int) void sethour(int ) void setMinute (int ) void setsecond(int int getHour( const; int getMinuteO const; int getSecondO const; void printUniversal0 const; void printstandardo万 P40110.13 private: int hour: int minute, int second, } o 2015, SEU. All rights reserved. 9
© 2009, SEU. All rights reserved. © 2015, SEU. All rights reserved. 9 10.2 const (Constant) Objects and const Member Functions class Time { public: Time( int = 0, int = 0, int = 0 ); void setTime( int, int, int ); void setHour( int ); void setMinute( int ); void setSecond( int ); int getHour() const; int getMinute() const; int getSecond() const; void printUniversal() const; void printStandard(); private: int hour; int minute; int second; };
10.2 const(Constant)Objects and const Member Functions void Time: test(Time &another) const minute 20 /不能修改 object printstandardo万 ∥/不能调用non- const成员函数 another minute= 20. ∥/oK,非同一 object another. sethour 6: ∥/oK 2015, SEU. All rights reserved. 10
© 2009, SEU. All rights reserved. © 2015, SEU. All rights reserved. 10 10.2 const (Constant) Objects and const Member Functions void Time::test(Time &another) const { minute = 20; // 不能修改object printStandard(); // 不能调用non-const成员函数 another.minute = 20; // OK,非同一object another.setHour(6); // OK }