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(12);		//OK, const变量只能调用const成员函数
    t.fun3();		//error, const变量不能调用非const成员函数

    system("pause");
}

我们编译一下:

根据代码里注释的分析,编译结果与我们的分析是吻合的。

在C++中
    -每个对象都有自己的成员变量
    -所有对象共享类中的成员函数 
    
-成员函数能直接访问成员变量
    -成员函数中通过隐式的this指针来指明当前所在的对象
 

#include <iostream>
#include <string>

using namespace std;

class test
{
private:

public:

    test* getPthis()
    {
    	return this;	//返回当前对象的this指针
    }
};

int main()
{
    test t1;
    test t2;

    cout << "&t1 = " << &t1 << endl << "t1.getPthis() = " << t1.getPthis() << endl << endl;
    cout << "&t2 = " << &t2 << endl << "t2.getPthis() = " << t2.getPthis() << endl;
    system("pause");
}

编译输出一下:

从输出我们看到,直接通过&获取对象的地址与通过成员函数返回的this指针值,是一样的,所以说C++中,类中的this指针就代表当前对象的指针,当我们在对象成员函数中通过this指针指向的变量,就是该对象对应的成员变量: this->m_value;这里的m_value,就是当前对象中的成员变量(每个对象都有自己的成员变量)。

总结:
    -const关键字能够修饰对象,得到只读对象
    -只读对象只能调用const成员函数
    -每个对象拥有各自的成员变量
    -所有对象共享类的成员函数
    -隐藏的this指针用于表示当前对象

猜你喜欢

转载自blog.csdn.net/lms1008611/article/details/81407586
今日推荐