C++之const成员函数

C++除了提供静态成员函数之外,他还提供了const函数。

const主要用于不对类的数据成员做出修改的函数。

由于const函数的隐藏参数this指针变成了const 类名*this,所以const函数不能修改类的数据成员的值,但可以使用类的数据成员。

这个const就非常适合get类型的函数,用于获取类的数据成员的值。

一般的写法是这样:

返回值 函数名(参数列表) const
{
    //函数体
}

实际中可能遇见下面这两种:

const 返回值 函数名(参数列表) 
{
    //函数体
}
返回值 const 函数名(参数列表) 
{
    //函数体
}

也就是说const写在哪儿并不影响它成为类的const成员函数。

下面是一个例子。

#include <iostream>
#include <cstdlib>

class s
{
public:
	s();
	~s();

	 void const fun1();
	void fun2();
private:
	int a;
	int b;
};

s::s() :a(12), b(3)
{
}

s::~s()
{
}

void const s::fun1()
{
	//	a = 10;		常函数不能修改类的数据成员

	//但是它可以修改自己内部的变量
	int q{ 1 };
	q = 111;
	std::cout << "this is one" << std::endl;
}

void s::fun2()
{
	std::cout << "this is two" << std::endl;
}

int main(int argc, char **argv)
{
	s a;
	a.fun1();
	a.fun2();
	return 0;
}

 

发布了222 篇原创文章 · 获赞 174 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/zy010101/article/details/105233263