You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
voidf1(const std::string& s); //pass by reference-to-constvoidf2(const std::string* sp); //pass by pointer-to-constvoidf3(std::string s); //pass by valuevoidg1(std::string& s); //pass by reference-to-non-constvoidg2(std::string* sp); //pass by pointer-to-non-const
常量正确性:避免意外修改不希望修改的东西
一般来说,const 作用于离它最近的左侧的类型,否则,作用于离它最近的右侧的类型
规则:read it backwards,即倒着读
建议:X 放在修饰符的右边
1.2 const 和 *
const X * ptr:ptr is a pointer to an X that is const
ptr 是一个指针变量,指向一个 X 的对象,但不能通过指针修改 X 对象, *ptr 只读
不能通过 ptr 调用 X 非 const 的成员方法,否则会有编译警告
声明
解释
描述
const int const0=96;
int is const
const1 是整型常量,不可再赋值
X * ptr
ptr is a pointer to an X
X 对象实例的指针
const X * ptr
ptr is a pointer to an X that is const
ptr 是一个指针变量,指向一个 X 的对象,但不能通过指针修改 X 对象, *ptr 只读
X const * ptr
同上
同上
X const const * ptr
同上
同上
const X const * ptr
同上
同上
X * const ptr
ptr is a const pointer to an X
ptr 是一个常量指针,指向一个 X 的对象,不能给指针再赋值,但是可以通过指针修改 X 对象,ptr 只读
const X & obj:obj is a reference to an X that is const
obj 是一个 X 对象的引用,但不能通过 obj 修改 X 对象
不能通过 obj 调用 X 非 const 的成员方法,否则会有编译警告
声明
解释
描述
const X & obj
obj is a reference to an X that is const
obj 是一个 X 对象的引用,但不能通过 obj 修改 X 对象, obj 只读
X const & obj
同上
同上
1.4 成员函数
在成员函数后加const避免在内部修改成员变量
classMyClass{
int m_var;
// modify m_var is not allowedvoidSomeMethod() const;
// the var pointed to by returned pointer and returned pointer is not allowed to altered// the var pointed to by given pointer and given pointer is const// modify m_var is not allowedconstint * constAnotherMethod(constint * const &) const;
// the return value must not be reference to a member of MyClass
std::string& BadMethod() const;
// the return value can be reference to a member of MyClassconst std::string& GoodMethod() const;
}
2 二重指针
声明
解释
描述
int ** pp
pp is a pointer to a pointer to an int
-
int ** const pp
pp is a const pointer to a pointer to an int
-
int * const * pp
pp is a pointer to a const pointer to an int
-
int const ** pp
pp is a pointer to a pointer to a const int
-
int * const * const pp
pp is a const pointer to a const pointer to an int