我在初学C++的时候经常会疑惑,为什么一些字符串处理函数的字符串参数都声明为const类型,我认为这是完全没有必要的,后来我在C++ ProPlus中找到了答案。
将指针参数声明为指向常量数据的指针有两条理由:
1、这样可以避免由于无意间修改数据而导致的编程错误
2、使用const是的函数能够同时处理const(如“中的字符串”)和非const数据,否则将只能接受非const数据。
#include<iostream>
using namespace std;
int findc(const char * str,char ch)
{
int count = 1;
while(*str)
{
if(*str == ch)
return count;
else
{
str++;
}
count++;
}
}
int main()
{
char ch = 'd';
char name[20] = "dghtql";
char * tail = "dghtql";
cout << findc(name,ch) << endl;
cout << findc(tail,ch) << endl;
cout << findc("dghtql",ch) << endl;
}
输出:
findc.cpp: In function 'int main()':
findc.cpp:22:19: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
char * tail = "dghtql";
^~~~~~~~
1
1
1
[Done] exited with code=0 in 14.184 seconds