有几种方法可以使用指针在变量中声明 const:
const char * // you can modify the pointer, not the item pointed to
char const * // you can modify the pointer, not the item pointed to
char * const // you can modify the item pointed to, not the pointer
const char const * // you cannot modify either
char const * const // you cannot modify either
const char * const // you cannot modify either
至于问题,这两个方法定义是重载,调用哪一个要看上下文。例如,如果调用者也在一个const
方法中,并且在它的一个成员上进行调用(谁是具有data()
方法的类的实例化),那么该const char * data() const
方法将被调用,调用者只能保存返回值在类型的变量中const char *
。这是一个例子:
class MyClass {
DataClass data_obj_; // has both 'data()' methods described in your question
...
void my_method () const { // within this const method, data_obj_ cannot be modified
const char * data = data_obj_.data(); // calls const method
...