Constant Member Functions

来源:互联网 发布:柳长街知乎 编辑:程序博客网 时间:2024/05/17 16:46

          Declaring a member function with the const keyword specifies that the function is a "read-only"

function  that does not modify 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 requried in both the declaration and definition.A constant

member function cannot modify anydata members or call any member functions that aren't constant.

Example

//Example of a constant member function

class Date

{

public:

Date(int mn,int dy,int yr);

int getMonth() const;        //A read-only function

void setMoth(int mn);        //A write function;cannot be const

private:

int month;

};

 

int Date::getMonth() const

{

return month;    //Doesn't modify anything

}

void Date::setMonth(int mn)

{

moth = mn;       //Modifies data member

}

 

 

原创粉丝点击