C++ 指针的常量说明符
我可以声明foocont T&var,这样我就知道var不会被更改 指针的等效格式是foocont T*var 在过去我尝试过这些,与迭代器/const_迭代器相关的错误激怒了我,我只是倾向于使用T*var而不考虑constannessC++ 指针的常量说明符,c++,pointers,constants,C++,Pointers,Constants,我可以声明foocont T&var,这样我就知道var不会被更改 指针的等效格式是foocont T*var 在过去我尝试过这些,与迭代器/const_迭代器相关的错误激怒了我,我只是倾向于使用T*var而不考虑constanness 是否有一个好的文档用于声明函数,该函数强制执行指针指向的内容不会更改?您已经拥有一个指针,它禁止指针对象的内容更改。您可以通过使用“向后读取”规则看到这一点: const T* var <===== left to right from this
是否有一个好的文档用于声明函数,该函数强制执行指针指向的内容不会更改?您已经拥有一个指针,它禁止指针对象的内容更改。您可以通过使用“向后读取”规则看到这一点:
const T* var <===== left to right from this read
内容如下:
var是指向T的常量指针
这里的区别是常数是var,而不是T;这意味着您可以通过取消引用var来更改T,但不能更改var指向的内容
当然,您可以同时拥有上述两项:
const T* const var
您已经拥有一个指针,它禁止被指针对象的内容更改。您可以通过使用“向后读取”规则看到这一点:
const T* var <===== left to right from this read
内容如下:
var是指向T的常量指针
这里的区别是常数是var,而不是T;这意味着您可以通过取消引用var来更改T,但不能更改var指向的内容
当然,您可以同时拥有上述两项:
const T* const var
从
关于常数的一个非常好的经验法则:
从右到左阅读声明
int const x; // x is a constant int
const int x; // x is an int which is const
// easy. the rule becomes really useful in the following:
int const * const p; // p is const-pointer to const-int
int const &p; // p is a reference to const-int
int * const * p; // p is a pointer to const-pointer to int.
自从我遵循这条经验法则以来,我再也没有曲解过这样的声明
:sisab retcarahc代表一吨,sisab nekot代表一吨:潮汐
同样,您可以将函数签名写入此规则:
void foo (int const * const p)
现在,p是指向const-int的const指针。这意味着在函数体中,不能让p指向其他对象,即不能更改指针,也不能更改它指向的对象
作为常量指针的p是真正只与函数体相关的信息,您应该从头文件中忽略此信息:
// foo.h
void foo (int const *p);
然后
从
关于常数的一个非常好的经验法则:
从右到左阅读声明
int const x; // x is a constant int
const int x; // x is an int which is const
// easy. the rule becomes really useful in the following:
int const * const p; // p is const-pointer to const-int
int const &p; // p is a reference to const-int
int * const * p; // p is a pointer to const-pointer to int.
自从我遵循这条经验法则以来,我再也没有曲解过这样的声明
:sisab retcarahc代表一吨,sisab nekot代表一吨:潮汐
同样,您可以将函数签名写入此规则:
void foo (int const * const p)
现在,p是指向const-int的const指针。这意味着在函数体中,不能让p指向其他对象,即不能更改指针,也不能更改它指向的对象
作为常量指针的p是真正只与函数体相关的信息,您应该从头文件中忽略此信息:
// foo.h
void foo (int const *p);
然后
@尤金:如果你能更具体一点。。。哪个错误?什么密码?@Eugene:如果你能说得更具体些。。。哪个错误?什么代码?