template中的const的问题。谢谢各位大哥了

sevown 2003-11-11 04:01:22
#include<iostream>
#include<string>
using namespace std;

template<typename elemtype>
elemtype* find(const elemtype* first,const elemtype* last,const elemtype &value)
{
if(!first||!last)
return 0;
for(;first!=last;++first)
if(*first==value)
return first;
return 0;
}

int main()
{
int a[8]={1,1,2,3,5,8,13,21};
double da[]={1.5,2.0,2.5,3.0,3.5,4.0};
string sa[]={"pooh","piglet","eeyore","tigger"};

int* pi=find(a,a+8,a[3]);
double* pd=find(da,da+6,da[3]);
string* ps=find(sa,sa+4,sa[3]);

cout<<&a[3]<<" a sequence:"<<pi<<" "<<&pi<<endl;
cout<<&da[3]<<" da sequence:"<<pd<<" "<<&pd<<endl;
cout<<&sa[3]<<" sa sequence:"<<ps<<" "<<&ps<<endl;

return 0;
}
若去掉参数中的const,应怎么办呢?
...全文
87 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Andy84920 2003-11-20
  • 打赏
  • 举报
回复
是不是模板在作怪?不会吧!
Andy84920 2003-11-20
  • 打赏
  • 举报
回复
elemtype* find(const elemtype* first,const elemtype* last,const elemtype &value)
{
if(!first||!last)
return 0;
for(;first!=last;++first)
if(*first==value)
return first;
return 0;
}

为什么返回的是first,它是一个const elemtype*, 而函数返回的是elemtype *
不是会有一个const 转换??

看EG:
int* find(const int* first,const int* last,const int &value)
{
if(!first||!last)
return 0;
for(;first!=last;++first)
if(*first==value)
return first;
return 0;
}
编译如下:const.C:7: invalid conversion from `const int*' to `int*'


为什么楼主的程序没问题呢?
agilecoder 2003-11-16
  • 打赏
  • 举报
回复
up
jeckyz 2003-11-16
  • 打赏
  • 举报
回复
不该去掉 const,应该尽可能多地使用它,大师们如是说的。上面给的那个 find 算法是符合逻辑的,那么为什么传一个非 const 参数给它又可以编译呢?分析一下就理解了:const 意味着是不可以更改的,不是吗?传一个非 const 参数给它,意味着这个参数在运算过程中是不改变的,这当然符合逻辑;但反过来,把一个 const 传给一个非 const又会是怎样的呢?意味着,一个不可以改来的“常量”有可能会在运算中修改,这当然是不符合语言规则的,编译能检测这般隐含的(当然是不符合逻辑的)错误,是件大好事才对!

嘿嘿,涂鸭的这些好像是从哪背出来的 :)
sevencat 2003-11-16
  • 打赏
  • 举报
回复
模板中的const有时候是假的.
虽然写了const但有的编译器还可以让你改.
binjuny 2003-11-16
  • 打赏
  • 举报
回复
还是不要去了,用const好
noirchloe 2003-11-14
  • 打赏
  • 举报
回复
被强制转型了......
你这样做会产生一些问题,当你使用一些iterator的时候会有warning,不过代码还是能跑的
fierygnu 2003-11-11
  • 打赏
  • 举报
回复
去掉就去掉了。

24,855

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧