const修饰的类成员函数

1、在类中用const修饰的成员函数有一个作用就是不能在该函数中修改类数据成员的值。

class Test
{
public:
	void fun(int x) const
	{
		x = 2;
		a = 3;  //error
		b = 4;  //error
	}
private:
	int a;
	int b;
};

 

2、对于const修饰的类对象,只能调用const修饰的成员函数,而不能调用非const成员函数。

#include <iostream>

using namespace std;

class Test
{
public:
	void fun(int x) const
	{
		x = 2;
	}

	void fun2()
	{

	}
private:
	int a;
	int b;
};


int main()
{
	const Test t;
	t.fun(1);
	t.fun2(); //error

	return 0;

}

        而对于非const修饰的类对象则可以调用任何public成员函数。如果是一对有无const的重载成员函数,非const类对象会调用非const成员函数。


你可能感兴趣的:(C++,类,对象)