Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

visual c++ - C++, Need Reason for error : cannot convert parameter 1 from 'char *' to 'const char *&'

Whey we cannot Convert pointer to a character ->TO-> a reference to a pointer to a constant character

I am interested in knowing the reason of syntax error when we call foo_ptr. When foo_char is allowed why not foo_ptr.
[Update 1.] I would be happy in knowing the reason that foo_char() is working, why foo_ptr() is not working .. What happens when pointer come in the picture.

[Update 2.] Didnt work in Dev C++ compiler version 4.9.9.2 too ..

//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;        
}        
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Suppose you had

void foo_ptr(const char * & ptr)
{         
    ptr = "readonlystring";
}        

You now call it as

    char *ptr;
    foo_ptr(ptr);
    *ptr = 0;

Suppose no error were raised. You are writing to a read-only string, violating the type system without any casts.

This is basically the CV version of How come a pointer to a derived class cannot be passed to a function expecting a reference to a pointer to the base class?.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...