Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / C++ 之 常量成员函数

类的常量成员函数(const member function), 可以访问类的数据成员,但是不能修改。1  声明在成员函数声明的参数列表后,加上 const 关键字,声明为常量成员函数(const member function),表明其不被允许修改类的数据成员下面代码,定义了一个 Date 类,分别以年、月、日的形式来表示日期class Date {
public:
    int day() const { return d; }
    int month() const { return m; }
    int year() const;
    void add_year(int n); // add n years
private:
    int d, m, y;
}; 1) 如果常量成员函数,企图修改类的数据成员,则编译器会报错// error : attempt to change member value in const function
int Date::year() const
{
    return ++y;
}2) 如果在类外面,定义常量成员函数,则 const 关键字不可省略// error : const missing in member function type
int Date::year()
{
    return y;
}2  调用一个常量成员函数,可以被 const 和 non-const 类对象调用; 而非常量成员函数(non-const member function),则只能被 non-const 型类对象调用。 void f(Date& d, const Date& cd)
{
    int i = d.year();    // OK
    d.add_year(1);        // OK
    int j = cd.year();    // OK
    cd.add_year(1);        // error
}3  this 指针  <C++ Primer> 中,有关于 const 后缀更详细的解释:  this 指针默认是指向 non-const 型类对象的 const 型指针,因此,不能将 this 指针和 const 型类对象绑定,即 const 类对象无法调用类的成员函数。  在成员函数声明的参数列表后加 const 后缀,表明其 this 指针指向 const 型类对象,如此, const 型类对象便可以调用常量成员函数了。 小结:1) 类成员函数声明中的 const 后缀,表明其 this 指针指向 const 型类对象,因此该 const 类对象,可以调用常量成员函数(const member function)2) 一个成员函数,如果对数据成员只涉及读操作,而不进行修改操作,则尽可能声明为常量成员函数参考资料: <C++ Programming Language_4th> ch 16.2.9.1 <C++ Primer_5th> ch 7.1.2 <Effective C++_3rd> Item 3本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-04/130365.htm