C++ class 中的 const 成员函数

const 修饰的成员函数  表示  不会修改class中的成员变量。

 

const 和 非-const 的成员函数同事存在时,

用户定义 const 类对象,调用 const 成员函数;

定义 非-const 类对象,调用  非-const 成员函数。

 

加上 const 的理由:

比如 string 中的[]重载,const string和string应该对应不同的操作。

 

#include <iostream>

class NN
{
public:
	NN() = default;

	//int p()
	//{
	//	std::cout << "1  " << __cplusplus << std::endl;
	//	return 1;
	//}

	int p() const
	{
		std::cout << "2  " << __cplusplus << std::endl;
		return 2;
	}
};

int main()
{

	NN n;
	n.p();

	const NN cn;
	cn.p();

	return 0;
}

  

posted @ 2019-11-24 12:08  路边的十元钱硬币  阅读(860)  评论(0编辑  收藏  举报