得分点:变量、指针、函数参数、成员、成员方法;
标准回答:const 的用法有很多:
1.用在变量身上,表示该变量只读,不能对它的值进行修改const int a=10;a=20;// 编译会报错,因为a只读,不能对它进行修改;
2.结合指针一起使用const int * p; // 常量指针 int * const p; // 指针常量 const int * const p; const int * p是常量指针,表示指变量p 所指向的内容不能修改,指针变量p的内容可以修改;int * const p 是指针常量,表示指针变量p的内容不能修改,指针变量p所指向的内容可以修改;const int * const p表示指针变量p的内容和所指向的内容都不可以修改;
3.const 用于函数参数 voidl foo (constint * p); void foo(const int & p);const 用于形参时说明形参在函数内部不能被改变,这是非常有用的,有时候函数参数传递指针或者引用,在函数内部不希望对指针和引用指向的数据进行修改,可以加上const;
4. 在类中修饰成员方法,防止在方法中修改非 static 成员 class A { public:
int a; void fun() const {a=20;// 错误,const 修饰的成员方法中不能修改非静态成员变量}}
5.const 修饰类的成员变量 class T { public: T():a(10) { } private: const int a; static const int b; };
const int T::b=20;类的成员变量可以分为静态的和非静态的,如果const 修饰的是静态的成员变量,可以在构造函数中对该变量进行初始化;如果 const 修饰的是静态的成员变量,则需要在类外对该变量进行初始化.。