Constant Member Functions C++ Specific 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.END C++ SpecificExample// Example of a constant member function class Date { public: Date( int mn, int dy, int yr ); int getMonth() const; // A read-only function void setMonth( 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 ) { month = mn; // Modifies data member }
任何不会修改类的成员函数都应该声明为const类型。如果在编写const成员函数时,不慎修改了数据成员,或者调用了其他非const成员函数,编译器将指出错误,这无疑会提高程序的健壮性。明白了么:)元旦快乐!
意思是:IsKindOf()这个函数不会修改类的成员函数。这句话有两种理解:
IsKindOf()这个函数不会修改类的成员
IsKindOf()这个函数不会修改类
那个对?
定义好的类怎么会被修改?
const 起一个检查函数确保其不能修改类的成员变量的作用。
若函数不修改类的成员变量也可不用const ,但用了以后更保险。
C++ Specific 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.END C++ SpecificExample// Example of a constant member function
class Date
{
public:
Date( int mn, int dy, int yr );
int getMonth() const; // A read-only function
void setMonth( 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 )
{
month = mn; // Modifies data member
}
给这个函数传入的this指针是const值。