A const object can only call const function
来源:互联网 发布:淘宝服装店铺定位 编辑:程序博客网 时间:2024/05/21 19:27
consider the following class
//=========================================================
class cal_date
{
public:
bool is_leap_year( void ) const ;
private:
int year ;
int month ;
int day ;
bool is_valid_date( void ) ;
} ;
bool cal_date::is_leap_year(void) const
{
bool IsLeapYear = false ;
if( is_valid_date() )
{
// code to check if it's a leap year
// ....
return ( IsLeapYear ) ;
} // end if
} // end is_leap_year
//=========================================================
There's something wrong with member function "is_leap_year()". The "is_leap_year()" is a const function which cannot change the properties of 'cal_date' class. On the contrary, "is_valid_date" is not a const function which can modify the properties of 'cal_date' class. Thus, a const function calling a non-const function can not make sure that the properties of a class won't be modified.
A solution to this problem is to modify the non-const function to a const function. For example, the member function "is_valid_date()" can be rewritten as following:
//=========================================================
// bool is_valid_date( void ) const ;
//=========================================================
Now we can call "is_valid_date()" in the function "is_leap_year()".
- A const object can only call const function
- const at the end of function and passing const object in a function call
- const的object和 const member function
- const function, function const
- only static const integral data members can be initialized within a class
- VS2005 error C2864 only static const integral data members can be initialized within a class
- const member function can return non-const type member vars
- const int function(const int a,const int b) const的意义
- Can I call a virtual function from a constructor?
- const int *const A;
- const char* const a
- Call to a member function display() on a non-object。。。。
- call to a member function display() on a non-object
- Call to a member function assign() on a non-object
- call/apply let const
- a pointer to a bound function may only be used to call the function
- a pointer to a bound function may only be used to call the function
- const int a; int const a; const int *a; int * const a; const int * const a;
- 我来也
- 用XSL进行日期格式转换
- Linux上的C/C++编译器gcc/egcs详解
- javascript的常用表单检查方法!
- 让我感觉很爽的CachedRowSet
- A const object can only call const function
- 3.24-3.25工作总结
- 2005年3月25日 晴,微风
- Python Note : 1
- java 帮助文档的各种方法怎么用?
- 由C#风潮想起的-给初学编程者的忠告
- 编程站点
- RichEdit中支持超链接的实现
- 第一次使用Blog