C++ const关键用法

来源:互联网 发布:js 封装好的confirm 编辑:程序博客网 时间:2024/04/29 10:08

请看以下代码,用代码说话

1.修饰数据类型

int iValue = 1;int const iConstValue = 1; // const int, same as const int iConstValue = 1;int const *pValue = &iValue; // a pointer to const int point to int//*pValue = 3; // error Expression must be a modifiable lvalue.int *pIntIter = const_cast<int*>(pValue);std::cout << *pValue; // 1std::cout << *pIntIter; // 1*pIntIter = 3; std::cout << *pIntIter; // 3std::cout << iValue; // 3std::cout << std::endl;iValue = 1; // resetpValue = &iConstValue; // a pointer to const int point to const int//*pValue = 4; // error Expression must be a modifiable lvalue.pIntIter = const_cast<int*>(pValue);std::cout << *pValue; // 1std::cout << *pIntIter; // 1*pIntIter = 3; // ?std::cout << *pValue; // 3std::cout << iConstValue; // 1std::cout << std::endl;int * const pValue1 = &iValue; // a const pointer to int pointer to int//int * const pValue1 = &iConstValue; // error//pValue1 = &iConstValue; // error Expression must be a modifiable lvalue.pIntIter = const_cast<int*>(pValue1);std::cout << *pValue1; // 1std::cout << *pIntIter; // 1*pIntIter = 3; // ?std::cout << *pValue1; // 3std::cout << iValue; // 3std::cout << std::endl;iValue = 1; // resetint const * const pConstValue1 = &iValue; // a const pointer to const int point to int//*pConstValue1 = 3; // error Expression must be a modifiable lvalue.pIntIter = const_cast<int*>(pConstValue1);std::cout << *pConstValue1; // 1std::cout << *pIntIter; // 1*pIntIter = 3; std::cout << *pIntIter; // 3std::cout << iValue; // 3std::cout << std::endl;iValue = 1; // resetint const * const pConstValue2  = &iConstValue; // a const pointer to const int point to const intpIntIter = const_cast<int*>(pConstValue2);std::cout << *pConstValue2; // 3std::cout << *pIntIter; // 3*pIntIter = 4; std::cout << *pIntIter; // 4std::cout << iConstValue; // 1std::cout << std::endl;
2.修饰函数
class Person{public:Person() : m_iAge(0) { }~Person() { }void SetAge(int iAge){//GetAge();// okm_iAge = iAge;}int GetAge() const{//m_iAge = 19; // error, cannot modify data member//SetAge(); // errorreturn m_iAge;}private:int m_iAge;};const Person someone;someone.GetAge();//someone.SetAge(1); // errorconst Person* pConstSomeone = &someone;Person* pSomeone = const_cast<Person*>(pConstSomeone);pSomeone->SetAge(3);std::cout << pSomeone->GetAge() << someone.GetAge() << std::endl; // 33


原创粉丝点击