常函数

1.格式

类型 函数名(形参) const

{}

#include <iostream>
#include <string>
using namespace std;

class Cperson
{
public:

	void show() const
	{
		cout << "we are csdn" << endl;
	}

};

int main()
{
	Cperson op;
	op.show();

	system("pause");
	return 0;
}

执行结果:

2.构造函数和析构函数不能定义为常函数

#include <iostream>
#include <string>
using namespace std;

class Cperson
{
public:
	Cperson() const
	{

	}

	~Cperson() const
	{

	}

	void show() const
	{
		cout << "we are csdn" << endl;
	}
};

int main()
{
	Cperson op;
	op.show();

	system("pause");
	return 0;
}

编译器报错:

3.常函数不能修改数据成员

特点:

1)可以输出,可以运算,但不能进行修改

2)这种不可修改只针对于类的数据成员,对于函数自身的参数可以进行修改

3)常函数的this指针变成了const 类名*

好处:

对函数功能有更明确的限定,例如只能输出,但不能进行修改

#include <iostream>
#include <string>
using namespace std;

class Cperson
{
public:
	Cperson():a(12)
	{

	}

	~Cperson()
	{

	}

	void show() const
	{
		a = 13;
		cout << "we are csdn" << endl;
	}

private:
	int a;
};

int main()
{
	Cperson op;
	op.show();

	system("pause");
	return 0;
}

编译器报错:

4.常对象

1)常对象格式:const 类名 对象名

2)常对象只能调用常函数,不能调用普通函数

#include <iostream>
#include <string>
using namespace std;

class Cperson
{
public:
	void show1()
	{
		cout << "I am ordinary" << endl;
	}
	void show() const
	{
		cout << "I am const" << endl;
	}
};

int main()
{
	const Cperson op;
	op.show();      //正确
	op.show1();     //错误

	system("pause");
	return 0;
}

编译器报错:

猜你喜欢

转载自blog.csdn.net/qq_33757398/article/details/81347665