const对象与const函数

来源:互联网 发布:淘宝全屏店招怎样制作 编辑:程序博客网 时间:2024/04/30 02:08

要指定const成员函数,我们只需在函数头后面附加const关键字即可。注意,我们只能对类成员函数这么做,对普通全局函数不能这么做。仅当某个函数是类成员时,将其声明为const才有意义,其作用是使该函数中的this指针成为const,这意味着我们不能在该函数的定义内在赋值语句左边写上类的数据成员——那将被编译器标记为错误。const成员函数不能调用同类的非const成员函数,因为那样也有可能修改当前对象。
当我们将某个对象声明为const之后,该对象可以调用的成员函数也都必须是const,否则程序将不能编译。
eg:

 CPointSource &operator=(const CPointSource &point_source)
    {
        m_attenuation = point_source.m_attenuation;
        m_lambda = point_source.m_lambda;
        m_point = point_source.m_point;
        m_wave = point_source.m_wave;
        return *this;
    }

注意: 只有常量静态整形值才能在类中进行初始化!!!

<script type="text/javascript"><!--google_ad_client = "pub-1307274723602242";/* 728x15, 创建于 09-3-6 */google_ad_slot = "3124229201";google_ad_width = 728;google_ad_height = 15;// --></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>