【发布时间】:2015-07-14 16:19:40
【问题描述】:
我做了一个 mystrcpy 函数,
void mystrcpy(char *&stuff, const char *&otherstuff){
for(int i=0; stuff[i]&&other[i]; i++){
stuff[i]=other[i];
}
}
还有一个主要功能:
int main(){
char *hello="hello";
mystrcpy(hello, "bye bye"/*<--i have no clue what data type this really is!!*/);
printf("%s\n", hello);
return 0;
}
它没有编译,并说“从'const char *'类型的右值对'const char *&'类型的非常量引用的初始化无效”......
当我这样做的时候:
const char *bye="bye bye";
mystrcpy(hello, bye);
它编译没有错误。
我需要知道为什么前一个不起作用,谢谢。
【问题讨论】:
-
松开函数签名中的 &,它们不会添加任何内容。
-
还有
char *hello="hello";???即使你确实编译了它,它也会在你的函数中对只读内存进行无效写入。如果上述代码行编译时至少没有警告,您需要将警告级别提高到迂腐的高度。 -
@hoholee12: 嗯,首先,为什么你的参数通过引用传递???有很多方法可以“修复”您的代码。这就是为什么不知道你的意图是没有意义的。
标签: c++ reference constants reference-binding