C++中的const对象与const成员函数

    在前边几章的内容中,我们知道C++的类中可以有const成员变量,并且还知道类中的const成员变量只能在初始化列表中初始化。同样,在C++中,还存在const对象以及const成员函数,const修饰的对象为只读对象,他们的特性如下:
    const成员函数的定义:需要在函数的声明定义后边加上const关键字
    -const对象只能调用const成员函数
    -const成员函数只能调用const成员函数
    -const成员函数中不能改变成员变量的值

下边以一段代码来验证一下:
 

#include <iostream>
#include <string>

using namespace std;

class test
{
private:
    int m_value;
public:

    void fun1(int value) const
    {
    	m_value = value;	//error, 不能在const成员函数中改变成员变量的值
        fun2();				//OK, const成员函数只能调用const成员函数
	    fun3();				//error, const成员函数不能调用非const成员函数
    }

    void fun2() const
    {
    	fun1(34);
    }

    void fun3()
    {
    	fun1(34);	//OK, 非const 成员函数中可以调用const成员函数
    }
};

int main()
{
    const test t;	//定义一个const对象
    t.fun1(
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值