aslucky

C++

 

Constant Member Functions

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.cpp
class 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 const
private:
   
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( 
741998 );
   
const Date BirthDate( 1181953 );
   MyDate.setMonth( 
4 );    // Okay
   BirthDate.getMonth();    // Okay
   BirthDate.setMonth( 4 ); // C2662 Error
}

posted on 2008-07-17 17:36 aslucky 阅读(257) 评论(0)  编辑 收藏 引用 所属分类: C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

统计

常用链接

留言簿(1)

随笔分类(6)

随笔档案(6)

文章分类(2)

文章档案(2)

Open source library

Software often use

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜