c++中的const/const_cast
2016-04-07 13:36
441 查看
const修饰普通变量
const修饰指针变量
const修饰指针变量指向的变量
const修饰类成员属性
const修饰类成员函数,const成员函数内部不能调用非const修饰的成员函数,不过在不作修改的情况下可以调用非const的类成员属性
const_cast的使用:
本段代码摘自Working Draft, Standard for Programming
Language C++ N4582
结构良好的代码应该不需要使用const_cast的。用错了不会报编译错误时,出现与编译器相关的未定义运行错误,非常危险。
const double PI = 3.14159f;
const修饰指针变量
double const *pPi = Π
const修饰指针变量指向的变量
const double *pPi = Π
const修饰类成员属性
const修饰类成员函数,const成员函数内部不能调用非const修饰的成员函数,不过在不作修改的情况下可以调用非const的类成员属性
float PI = 2.14; float getPi() { PI += 1; return PI; } class CA { private: const int a; int b; public: CA() :a(1), b(2) {} int getA() const { // b++; // const函数不能修改非const类成员属性 int c = a+b; // const函数能调用非const类成员属性 getPi(); // const函数可以调用类外部非const函数 return a; } void getCA() // const // const函数内部不能调用非const类成员函数 { getA(); getB(); } int getB() { // a++; b += 2; return b; } }; void test() { CA ca; cout << "ca.getA() : " << ca.getA() << endl; cout << "ca.getB() : " << ca.getB() << endl; }
const_cast的使用:
本段代码摘自Working Draft, Standard for Programming
Language C++ N4582
int i = 2; // not cv-qualified const int* cip; // pointer to const int cip = &i; // OK: cv-qualified access path to unqualified *cip = 4; // ill-formed: attempt to modify through ptr to const int* ip; ip = const_cast<int*>(cip); // cast needed to convert const int* to int* *ip = 4; // defined: *ip points to i, a non-const object const int* ciq = new const int (3); // initialized as required int* iq = const_cast<int*>(ciq); // cast required *iq = 4; // undefined: modifies a const object
结构良好的代码应该不需要使用const_cast的。用错了不会报编译错误时,出现与编译器相关的未定义运行错误,非常危险。
相关文章推荐
- 读深入C++对象模型的总结
- C++三元运算符?:
- C++第3次作业
- 機器學習基石(Machine Learning Foundations) 机器学习基石 作业三 Q13-15 C++实现
- C++作业3
- c++ PrimerPlus 第六版中文版编程习题答案
- 第1课 学习 C++ 的意义
- 第四次程序设计作业 C++计算器计算及命令行的使用 前缀表达式方法实现
- wstring
- C++从标准输入读取一行字符串
- 在C++中测试文件的读取与写入
- const 修饰指针的问题
- 第五届蓝桥杯决赛C\C++B组——生物芯片
- [undefine reference to...]c++ 已经引用头文件的情况编译显示未定义
- C语言字母频率统计
- C++中Sting类的深拷贝
- C++引用的使用
- C++中运算符的重载
- C++ vector用法
- c++第三次实验——个人所得税计算器