现实生活中使用的常量指针
Constant pointers used in real-life
亲爱的堆栈溢出社区
我试图更好地理解指针,遇到了一个问题:
问:我们什么时候可以使用常量指针?给出一个真实场景的示例并给出一些代码。
我在尝试查找和理解常量指针代码在现实生活中的使用位置以及所涉及的代码时遇到了问题。我不确定我的代码是否符合我的示例的标准。我尝试了以下方法:
我的回答:
1- 定义:
常量指针是无法更改其所持有地址的指针。
2-示例:
如果您想查找存储在手机联系人中的特定号码。而不是复制整个联系人列表(及其号码(,然后检查该特定号码。只需按住其地址并检查原始联系人列表(如果该号码在那里(。
3- 代码:
int main(){
const int* number = 032 ... ;
bool found = false;
Vector<int> contactList = { 031 ... , 032 ... , 072 ... };
for(int i=0; i < contactList.size(); i++){
if( *number == contactList[i]){
valid = true;
}
}
if(valid){
cout<< "Number found"<<endl;
} else{
cout<< "Number NOT found"<<endl;
}
}
常量指针和常量指针是不同的东西:
常量指针本身是常量。除了它已经指向的东西之外,它不能指向任何其他东西,因为它指向的东西可能会被改变:
int i = 5;
int *const p1 = &i; // a const pointer
++*p1; // valid code. i is now 6
int j = 0;
p1 = &j; // error
指向 const 本身的指针可能指向不同的东西,但它假设它指向的所有内容都是 const,因此它不允许更改它们:
int i = 5;
const int * p2 = &i; // a pointer to const
++*p2; // error
int j = 0;
p2 = &j; // valid code. p2 is now pointing to j
我假设你的问题是"为什么有人会使用假设一切都是常量的指针?可能有很多原因。其中之一是,当您将const int *
视为函数参数时,您知道此函数不会弄乱您的变量。函数返回后,它将保持不变。这基本上就是我们使用 const 的原因。我们可以不更改变量,但是通过将它们声明为const,我们知道编译器将确保我们的变量不会因错误或误解或其他任何事情而更改。
指向常量或常量指针的指针?
您需要注意定义常量指针的方式。 因为常量指针不是指向常量的指针。
static int table[10];
const int* number = table; // non const pointer to const
int * const number2 = table; // const pointer to non const
number++; // this is allowed because the pointer is not const
*number += 2; // this is NOT allowed because it's a pointer to const
number2++; // this is NOT allowed because the pointer is const
*number2 +=2; // this is allowed because the const pointer points to a non const
顺便说一下,小心前导 0,因为它们意味着八进制表示法:
cout << 032 <<endl; // displays 26 in decimal since 032 is octal notation
指针、地址和值
请注意指针和指向的值之间的区别。 幸运的是,C++禁止这样做可以保护您:
const int* number = 032; // compiler error
如果要保留指向特定值的指针:
int myvalue=032;
const int* number = &myvalue; // ok as long as you remain in scope
指向矢量元素时的注意事项
最后但并非最不重要的一点是,如果您想使用指向矢量元素的指针,请注意,在某些情况下,矢量元素的地址可能会更改(指针无效(,例如当矢量需要增长时。
您要执行的操作示例
现在让我们把所有这些放在一起,这里有一个稍微修改的程序:
const int * number; // const to avoid accidental overwrite
int search; // value to search for
cout<<"What number are you looking for ? ";
cin>>search;
for(int i=0; i < contactList.size(); i++){
if( contactList[i] == search){ // compare values
number = &contactList[i]; // set pointer
found = true;
}
}
// if the vector is not modified, you may use the pointer.
if(found){
cout<< "Number found: "<< *number <<endl;
}
else{
cout<< "Number NOT found"<<endl;
}
- 将常量指针引用绑定到非常量指针
- 如何使用数据对象上的常量指针初始化类
- 为什么我收到"从常量指针到指针的转换无效?
- C++/QT:使用指向私有成员的常量指针作为只读数据共享
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 为什么C++中没有常量引用,就像常量指针一样?
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 将常量指针强制转换为非常量
- 带有常量指针的矢量构造函数示例
- 什么是常量指针常量引用类型的参数?(const X* const & p)
- 在多线程函数中返回共享的常量指针会导致计时问题吗?
- 常量指针上的混乱
- 使用 static_cast 时指向常量指针的原因
- 如何在C++中定义常量指针数组?
- 测试此指针的常量指针性质
- 当常量指针用作函数的参数时
- C++ - 无法将顶部常量指针分配给另一个非常量指针
- 在不同类型之间转换常量指针
- 解构常量指针?
- 为什么 std::vector<>::const_reference 可以转换为非常量指针?