码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 之 const member function

时间:2016-04-18 18:43:46      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:

  一个常量成员函数(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

 

C++ 之 const member function

标签:

原文地址:http://www.cnblogs.com/xinxue/p/5405362.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!