close
const通常代表的就是宣告該物件不可以變動 ,
像 const a = 3 , 就是宣告a為常數3 , 不可以更動 .
而 function (const a , const b) , 就是說在這個function裡面 , 不可以變動到a與b的值.
另外 , 像
void A::foo() const
{
cout << "I : " << _i << endl;
}
又稱為const member function , 其意義就是限制該function只能取得資料 , 不可以改變資料 (read-only) ,
另外 , 在這個const member function中 , 也不能呼叫任何不是 const 的member function.
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. A constant member function cannot modify any non-static 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( 7, 4, 1998 ); const Date BirthDate( 1, 18, 1953 ); MyDate.setMonth( 4 ); // Okay BirthDate.getMonth(); // Okay BirthDate.setMonth( 4 ); // C2662 Error }
全站熱搜