Constant Member Functions

来源:互联网 发布:新世纪网络平台 编辑:程序博客网 时间:2024/05/19 10:42

Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called.

To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. The const keyword is required in both the declaration and the definition. A constant member function cannot modify any data members or call any member functions that aren't constant.

// constant_member_function.cppclass Date{public:   Date( int mn, int dy, int yr );   int getMonth() const;     // A read-only function   void setMonth( int mn );   // A write function; can't be constprivate:   int month;};int Date::getMonth() const{   return month;        // Doesn't modify anything}void Date::setMonth( int mn ){   month = mn;          // Modifies data member}int main(){   Date MyDate( 7, 4, 1998 );   const Date BirthDate( 1, 18, 1953 );   MyDate.setMonth( 4 );    // Okay   BirthDate.getMonth();    // Okay   BirthDate.setMonth( 4 ); // C2662 Error}

原创粉丝点击