#include<iostream>
using namespace std;
const int* find(int val,const int* t, int n);
int main(){
int a[]={2, 4, 6};
int* ptr;//不是const类型
ptr=const_cast<int*>(find(4, a, 3));//去掉const类型
if(ptr == 0)
cout<<"not found"<<endl;
else
cout<<"found: value= "<<*ptr<<endl;
return 0;
}
const int* find(int val, const int* t, int n)
//确定val在数组中的位置,并以const指针返回其地址
{
int i;
for(i=0;i<n;i++)
if(t[i] == val)
return &t[i];
return 0;//not found
}
C++ const_cast强制去掉常量属性
最新推荐文章于 2024-09-01 16:08:06 发布
本文展示了一个使用C++编写的简单程序示例,该程序通过一个名为find的函数来查找数组中特定值的位置,并使用const_cast去除常量限定符以允许非const指针指向const对象。此程序为理解如何在C++中处理const性和指针提供了实践指导。
1112

被折叠的 条评论
为什么被折叠?



