c++笔记——const用法举例

1.使用const修饰变量

使用规则:
1)const离谁近,谁就不能被修改;
2)const修饰的变量,必须同时进行初始化
下面举例说明:

//例一:
int const x = 5;   //x的值为5且不可改变.   等效于  const int x = 5; 
//例二:
int a = 5;
int const *p = &a;   //指针p指向的值为5且不可改变,但p的地址可以改变
//例三:
int a = 5, b = 6;
int * const p = &a;       //指针p的地址不可改变,但p的值可以改变
*p = 10;                 //合法,此时*p和a的值都变成了10
p = &b;                  //不合法,p的地址不可变

2.使用const修饰成员函数

在类中定义一些const成员函数,是为了防止这些成员函数意外修改类中的数据成员。
注意:const放在成员函数的末尾,如:int GetCount(void) const;
下面举例:

class Stack
{
private:
	int m_num;
	int m_data[100];
public:
	void Push(int elem);
	int Pop(void);
	int GetCount(void) const;      //定义const成员函数
};
 
int Stack::GetCount(void) const
{
	++m_num;   //编译报错,GetCount()不可修改数据成员
	return m_num;
}

猜你喜欢

转载自blog.csdn.net/qq_43145072/article/details/86574018