C++回顾(1)——const的用法

说明:const是属于左结合的类型修饰符,这里只讲怎么使用。

1、const 变量

    //定义Const变量  常量
    const int value1  = 1;  // value1不可变
    int const value2  = 2;  // value2不可变</span>

2、const与指针 

    const int * p_str1 ;    // *p_str1 不可变    p_str1是可以改变的
    int * const p_str2 ;    //  p_str1 不可变    *p_str1是可以改变的
    const int * const p_str3;//  p_str1 不可变   *p_str1 不可变</span>

      上述中:const 的指针可以接受 const指针和非const指针, 但非const的指针 只能接受非const的指针,所以 const指针的能力更强大些。



3、函数中的const

     1)、const修饰函数的参数

    void function_1(const int value);     // value 的值不可改变
    void function_2(const int * p_value); // (*p_value) 的值不可改变(注意括号)
    void function_3( char * const p_str); // p_str的值不可改变(这里的p_str是指针变量)
     2)、const修饰函数的返回值

    const int function_4();     // 这里无意义
    const int  * function_5();  // const int * p = function_5();
    int * const function_6()    // int * const p = function_6();

以上C/ C++均可。


以下属于C++内容:

4、const与引用

     这里怎么感觉都不太好讲清楚,又不想写太长,见下一篇中讲解到引用时在具体说明。


5、类相关的const

class A
 {
 public:
	 A(int x):value(x){};
	 int b()
	 {
		 //value++;	// Error value不可改变
		 return value;
	 };

	 int c() const        // 修饰成员函数
	 {
		 return value;
	 };

private:
	 const int value;    // 修饰成员变量

 };
    const A a;
    a.b();    // Error
    a.c();    // OK
    // 所以 const对象只能调用const成员函数




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值