我们不能将指针转换为字符->TO-> 对指向常量字符的指针的引用
我很想知道调用 foo_ptr 时出现语法错误的原因。当 foo_char 被允许时,为什么不 foo_ptr。
[更新 1.] 我很高兴知道 foo_char()
工作的原因,为什么 foo_ptr()
不工作.. 当指针进入时会发生什么图片。
[更新 2。]
在 Dev C++ 编译器版本 4.9.9.2 中也没有工作..
//code
//OS : Win XP
//Env: VC++ 2008
//NOT ALLOWED
void foo_ptr(const char * & ptr) //reference to a pointer to a constant character
{
return;
}
//allowed
void foo_char(const char & p_Char) //reference to a constant character
{
return;
}
int main()
{
char ch = 'd';
char *ptr = "anu";
foo_char(ch);
foo_ptr(ptr); //NOT ALLOWED syntax error, vc++, 2008
return 0;
}
最佳答案
假设你有
void foo_ptr(const char * & ptr)
{
ptr = "readonlystring";
}
你现在称它为
char *ptr;
foo_ptr(ptr);
*ptr = 0;
假设没有引发错误。您正在写入只读字符串,违反了没有任何强制转换的类型系统。
这基本上是 How come a pointer to a derived class cannot be passed to a function expecting a reference to a pointer to the base class? 的 CV 版本.
关于C++,需要错误 : cannot convert parameter 1 from 'char *' to 'const char *&' 的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7850843/