C++ 之 const 修饰符用法 详解!

const 常量限定修饰符,它把一个对象转换为常量( constant )。 const 对象必须初始化而且是在定义的同时。初始化后的 const 对象(或指针)是不能修改的。


例1:

int i = 0;
	const int j = 0; // int const j = 0;
	const int *p;  // int const *p ;可改变p但不能改变*p
	int* const p = &i;  //可改变*p但不能改变p
     const int * const p = &i; // int const  * const p = &i; p,*p都不能改变


例二: 为什么错误,为什么正确? 大家自己思考

class Test{
public:
	const int i; //正确
	int & j;     //正确
	
};

int main(){
	const int i; //编译错误  error: uninitialized const 'i'
	int & j;     //编译错误 
}

关于初始化:

一般情况下:const对象必须初始化而且是在定义的同时

如果是在类中定义的, 即常数据成员,必须要在初始化列表进行初始化!

class Test{
public:
	const int i;
	int & j;
	Test(int a,int b):i(a),j(b){
	}

};


const 修饰指针: 如果一个变量已被声明为常变量,只能用指向常变量的指针变量指向它。
int main()
{
	const char c[] = "boy";
	const char * p1;
	p1 = c;
	char * p2 = c; //错误! error: invalid conversion from 'const char*' to 'char*' 
	return 0;
}


const 修饰成员函数: const 类对象只能调用 const 成员函数,而 const 成员函数不能修改类的成员变量 const 成员函数若要修改某成员变量,就必须用 mutable 修饰该成员变量。

class Test{
public:
	int i;
	void f() const{ //错误!
		i++; 
	}
};

 error: increment of member 'Test::i' in read-only object

例2:

class Test{
public:
	int i;
	int get() const{
		return i;
	}
	void set(int a){
		i = a;
	}
};

int main(){
	const Test t; // error: uninitialized const 't'
}

int main(){
	Test t1;
	const Test t2 = t1;
	t2.get(); /正确,不能调用 t2.set();  如果把get()方法的const修饰去掉,此句也是错误!

}


const 修饰函数参数:若是按值传递参数,不要用 const 修饰,因为这没有作用,而且容易产生误导。按值传递的函数参数最好是改为 const 的引用参数

class Test{
public:
	int i;
	int get() const{
		return i;
	}
	void set(const int a){
		i = a;
		a++; // error: increment of read-only parameter 'a'
	}
};



	int n;
	static int _n;

	void f(int = n);//错误!!!
        void f2(int = _n);

: error C2648: 'n' : use of member as default parameter requires static member



const 修饰函数返回值:当函数返回值不是内部类型时,通常用 const 修饰返回值。因为函数返回值是个 临时对象 ,这样有助于编译器检查出调用者试图修改这临时对象。


const 的目的是正确性,而且没有运行的开销(编译时完成)。在 C++ const 的正确性仅仅是类型信息的另一种形式,是把程序员头脑里的正确信息语言化。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值