A const object can only Call Const Function

xiaoxiao2021-03-06  18

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 ISLAPYEAR = 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 can not 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 this the .. ..

A Solution To this probem is to modify the non-const function to a const function. For example_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 ()".

转载请注明原文地址:https://www.9cbs.com/read-42184.html

New Post(0)