回 帖 发 新 帖 刷新版面

主题:关于函数的问题

请问:
      在VC++的编程中经常会看到这样的函数定义,
例如:
      CString GetToolTipText() const;
请问这const代表的含义?

回复列表 (共3个回复)

沙发

这是一个常成员函数,在这个函数里,不能改变他所调用的对象的任何属性。一般用来返回一个值。

板凳

建议老兄有时间看看msdn。

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++ Specific

Example

// 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
}

--------------------------------------------------------------------------------
Send feedback to MSDN.Look here for MSDN Online resources

3 楼

英语不太行
只看懂了一小部分....

我来回复

您尚未登录,请登录后再回复。点此登录或注册