C++ 之 const 修饰符用法 详解!
2012-11-02 00:07
736 查看
•const:常量限定修饰符,它把一个对象转换为常量(constant)。const对象必须初始化而且是在定义的同时。初始化后的const对象(或指针)是不能修改的。
例1:
例二: 为什么错误,为什么正确? 大家自己思考
关于初始化:
一般情况下:const对象必须初始化而且是在定义的同时。
如果是在类中定义的, 即常数据成员,必须要在初始化列表进行初始化!
•const修饰指针:如果一个变量已被声明为常变量,只能用指向常变量的指针变量指向它。
•const修饰成员函数:const类对象只能调用const成员函数,而const成员函数不能修改类的成员变量。const成员函数若要修改某成员变量,就必须用mutable修饰该成员变量。
例2:
•const修饰函数参数:若是按值传递参数,不要用const修饰,因为这没有作用,而且容易产生误导。按值传递的函数参数最好是改为const的引用参数。
•const修饰函数返回值:当函数返回值不是内部类型时,通常用const修饰返回值。因为函数返回值是个临时对象,这样有助于编译器检查出调用者试图修改这临时对象。
•const的目的是正确性,而且没有运行的开销(编译时完成)。在C++里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的正确性仅仅是类型信息的另一种形式,是把程序员头脑里的正确信息语言化。
相关文章推荐
- C++中的const成员函数(函数声明后加const,或称常量成员函数)用法详解
- C++中const的用法详解
- C++学习之const成员函数(函数声明后加const,或称常量成员函数)用法详解
- C++中const的用法详解
- C++中的const成员函数(函数声明后加const,或称常量成员函数)用法详解
- C++中const用法详解
- C/C++ 中 const 修饰符用法总结
- C#中const 和 readonly 修饰符的用法详解
- C++ const的用法详解
- C++中的const成员函数(函数声明后加const,或称常量成员函数)用法详解
- C++中const的用法详解
- 详解C++中const_cast与reinterpret_cast运算符的用法
- C/C++中修饰符const、extern、static、volatile的用法【解决了】
- C++中的const成员函数(函数声明后加const,或称常量成员函数)用法详解
- C/C++中修饰符const、extern、static、volatile的用法【解决了】
- 关于c++中const的用法详解
- [原]C++ const关键字用法详解
- C++中const用法详解
- C/C++中修饰符const、extern、static、volatile的用法【解决了】
- c++中const的用法详解