请介绍一下c++中的const语法。(300分)

L

lps

Unregistered / Unconfirmed
GUEST, unregistred user!
下面的代码来自某一本书,是用来实现c++中strstr库函数的,出现如下错误:
error C2440: 'initializing' : cannot convert from 'const char *' to 'char *'
(请不用给我翻译这段ENGLISH)
#include <iostream.h>
char * strstr( const char * string, const char * pattern)
{
for(;*string;string++){
for (char * s=string,* p=pattern;
*s==*p&amp;&amp;*p&amp;&amp;*s;
s++,p++)

if(!*p)
return string;
}
return 0;
}
void main()
{
char * s1="this a test",*s2="is";
cout<<strstr(s1,s2)<<endl;
}
 
我对C++也不熟悉,谈谈自己的看法吧
>>error C2440: 'initializing' : cannot convert from 'const char *' to 'char *'
我想,这个错误主要来自于“常量类型const”,就是不能将常量类型向变量类型转换。
有关const和char*一起使用的几种用法,要注意下面几点(我从书上给你找到的):
1. const char* pc = "abcd";
指针pc所指定的对象"abcd"在程序中不能再改变。
pc[1] = 'v';
//将b换为v,错误
pc = "xyz";
//将pc指向"xyz",正确
2. char* const pc = "abcd";
pc所指的对象在程序中不能再改变。
pc = "xyz";
//错误
pc[1] = 'v';
//正确
3. const char* const pc = "abcd";
指针pc和它指向的对象都不能改变。
 
但是这里是指针啊!
 
我个人认为:
错误在这里
#include <iostream.h>
char * strstr( const char * string, const char * pattern)
{
for(;*string;string++){
for (char * s=string,* p=pattern;
*s==*p&amp;&amp;*p&amp;&amp;*s;
s++,p++)

if(!*p)
return string;
//这里***
}
return 0;
}
在C++中,在函数中,只要遇到return语句,马上就返回了。
string是传进来的const参数,好像不能返回它,你可以将这一行注释掉,看看能否编译过去
 
实际上char * s=string,* p=pattern;
也有两个错,这里要编译通过只要全部定义为const char * (包括返回值),或者是全部
不要const.
我想知道的是关于这一部分语法的是如何规定,因为我的那本书有点老了,MSDN 98上没找到。
 
>>char * s=string,* p=pattern;
??这里没有错呀!
 
他们(tc++ 3.0 &amp;
vc++ 6.0)都是这样拒绝进行这样的转换的(赋值时要试图转换的),
return时也一样的。
 
>>他们(tc++ 3.0 &amp;
vc++ 6.0)都是这样拒绝进行这样的转换的(赋值时要试图转换的),
>>return时也一样的。
这就是我上面说的,strstr的参数是const的,而返回值不是const,所以,不能用return直接返回。
这在其他数据类型也是一样的呀,和return本身没有什么关系啊!
 
from 'const char *' to 'char *'的转换为什么不能进行?
 
string 是一个指针,他指向的是const char,对吧?
 
>>from 'const char *' to 'char *'的转换为什么不能进行?
当然不可以啦!!'const char *' 只能指向常量啊!!而'char *'是可变的呀!!
比如:
const char* s = "string";
char* a = "dfdf";
a = s;
//错误
s = "ddddd";
//正确
 
那如下典型的指针转换为什么就可行((void *) to (long *) )
buffer = (long *)calloc( 40, sizeof( long ) );
如果谁的书上明确讲了这里的转换规则,劳架type一下。
 
(void *) to (long *)
这和上面的问题没什么关联啊?!其中long*,什么数据类型的指针都可以啊,
它是可变的指针指向另一个可变的指针啊,可以啊
 
[red]找了好半天[/red]
from msdn 98:
C++do
es not supply a standard conversion from a const or volatile type
to a type that is not const or volatile. However, any sort of conversion
can be specified using explicit type casts (including conversions that
are unsafe).
强制转换就行了!
 
唉!这分得的惭愧啊![:(]
 

Similar threads

I
回复
0
查看
684
import
I
I
回复
0
查看
602
import
I
I
回复
0
查看
684
import
I
顶部