本文共 1176 字,大约阅读时间需要 3 分钟。
char p[] = {"1233"};const char* ptr = p;const char* str = "awk";
其中str指向字符串常量,存储在代码段,ptr指向数据段。const 修饰不能通过指针修改所指之物。但是指针的指向可以修改。
char s[] ={"5678"};ptr = s; //上述指针指向s
同时使用const修饰指针和所指向之物时:
const char * const ppt = s;
class Exa{ public: //...构造析构 const char& operator[](std::size_t pos) const{ ... //运算 return arr[pos]; } char &operator[](std::size_t pos){ ... //运算 return arr[pos]; } char &operator[](std::size_t pos) const{ ... //运算 return arr[pos]; } private: const int SIZE = 100; char *arr;};
const与non-const会构成重载,第一个operator[]中的const是限制函数不可修改成员并且不可修改返回值,第二个未进行const限制,第三个const限制不能再函数中修改成员,但是它返回的引用会在函数外部进行对函数内部的修改,相当于自己将成员的内部暴露在外,所以一般不应用这样的修改方式。
class Exa{ public: //...构造析构 const char& operator[](std::size_t pos) const{ ... //运算 return arr[pos]; } char &operator[](std::size_t pos){ return const_cast(static_cast (*this)[pos]); } private: const int SIZE = 100; char *arr;};
所以如上,一般只保留前两种的[]的重载,但是这个重载在功能上的重复太多,有一点代码膨胀的嫌疑,所以将第二个非const的重载中将const移除。解释:添加const的转型使用static_cast<>进行了一次安全转型(将non-const对象转换为const对象),使用const_cast<>进行了一次移除const的操作。
const不仅可以作用于成员方法,也能作为成员对象,SIZE,给定初值,构造时使用。转载地址:http://pcxgj.baihongyu.com/