"指针到常量"有什么用?
What is the use of 'pointer to constant'?
我的问题是,根据我的样本,我已经能够通过指向常量变量的指针指向非常量变量。我的示例是这样的:-
int tobepointed = 10;
int tobepointed1 = 11;
int const *ptr = &tobepointed;
cout << "nPointer points to the memory address: " << ptr;
cout << "nPointer points to the value: " << *ptr;
tobepointed = 20;
cout << "nPointer points to the memory address: " << ptr;
cout << "nPointer points to the value: " << *ptr;
ptr = &tobepointed1;
cout << "nPointer points to the memory address: " << ptr;
cout << "nPointer points to the value: " << *ptr;
现在这段代码可以正常运行,没有任何编译或运行时错误。还要考虑*ptr指针。如果我像任何普通指针一样声明ptrint *ptr;
然后输出也是相同的,所以为什么我们需要"指针指向常量"的概念?
是的,我同意"常量指针"的概念,但是"概念指针"看起来没有用处。
指向常量的指针应该指向…一个常量int。你的程序编译了,因为你指向的是tobepointed
,而不是int
。
如果您声明它为const int
,那么指向它(不强制转换)的唯一方法是使用const int*
:
const int tobepointed = 10;
const int* ptr = &tobepointed;
如果你试图创建非const指针:
const int tobepointed = 10;
int* ptr = &tobepointed;
编译器会报错:
错误:从'const int*'到'int*'的转换无效
相关文章:
- #定义c-预处理器常量..我做错了什么
- 什么时候在C++中返回常量引用是个好主意
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- C 中的常量限定符和 C++ 中的常量限定符有什么区别?
- 常量公共成员有什么问题?
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 什么时候可以使用常量装饰调用我的重载函数?
- 使用什么代替"静态常量 TCHAR *"
- 常量字符*的性质是什么?
- 初始化不是整数的巨大常量多维数组的最佳方法是什么?
- 第二个常量在运算符函数中做什么?
- 常量成员和没有setter的私有成员之间有什么区别
- 什么是常量指针常量引用类型的参数?(const X* const & p)
- C++:允许临时对象调用非常量成员函数的设计理念是什么?
- 从模块导出全局常量的正确方法是什么?
- 有没有办法声明一个公共静态常量,该常量将使用 constexpr 在源文件中定义(有什么区别)?
- 有什么区别 - 常量 int x = 5000;和常量整数 x = 50'00;在C++?
- 出于什么原因,有必要将常量左值引用绑定到右值?
- 什么是可变常量?