const在c++中的用法分析

#include <iostream>

using std::cout;
using std::endl;

int main()
{
 const double rollwidth = 21.0;
 const double rolllength = 12.0*33.0;

 const char* pstring = "I am chinese";
 char* const qstring = "hello world";
 char const *mstring = "OK";
 
// pstring[1] = 'E';
 pstring = "he is chinese too";
 mstring = "NO";
 //qstring = "hello china";
 //qstring = "a good";
 //pstring = qstring;
    //rollwidth = 0.0;
 //qstring = pstring;
 char c = qstring[0];
 
 cout << "This rollwidth is " << rollwidth << endl;
 cout << "This rolllength is " << rolllength << endl;
 cout << "This qstring is " << mstring << endl;
 cout << "The char c is" << c;

}
    对于const char* 和 char* const之间的分析,如代码中的const char* pstring = "I am chinese"定义初始化后“I am chinese”这个变量为常量只读,如果用pstring[1] = 'E'则
会出现编译错误;
    代码中char* const qstring = "hello world";则指针qstring 是个常量,不能作为左值,如qstring = "hello china";则编译器会报错---不能给常量赋值;
    对于const double rollwidth = 21.0,其中rollwidth是常量,因而不能作为左值。
对于const char* pstring 和 char const* pstring 本质是一样的。

你可能感兴趣的:(const在c++中的用法分析)