2011-10-21 89 views
12

Whey我們不能將指針轉換爲字符 - > TO->指向常量字符的指針C++,需要錯誤原因:不能將參數1從'char *'轉換爲'const char *''

當我們調用foo_ptr時,我有興趣知道語法錯誤的原因。當foo_char被允許時爲什麼不是foo_ptr。
[更新1]我會很高興知道foo_char()正在工作的原因,爲什麼foo_ptr()不工作..當指針進入圖片時會發生什麼。

[更新2]中開發的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;   
}   
+0

也許解析器是錯誤的,試一下'foo_ptr((const char *)&ptr' – RedX

+1

在VC2010上編譯好的一切都可能是固定的bug? – atoMerz

+0

@RedX:謝謝輸入,void foo_ptr((const char * )PTR)給了錯誤C2065:未聲明的標識 – anubhav16

回答

2

用更多示例修改: Raymond Chen提供了正確的答案。通過傳遞非const指針(char *)作爲const指針的參考參數(foo_ptr(const char * &param)),您可能會返回一個常量指針類型(const char *),編譯器將不允許您這樣做。

這有一個Raymond Chen的例子,但我試圖解釋怎麼會事錯的,如果它通過增加額外的註釋和代碼編譯:

void foo_ptr(const char * & ptr) 
{   
    //Valid assignment, and the char * is now pointing to a const 
    //array of "readonlystring" 
    ptr = "readonlystring"; 
} 

... 
//inside main 
char *ptr = malloc(10*sizeof(char)); 
//See you can edit ptr, it's not const. 
ptr[0] = 'a'; 
ptr[1] = 'b'; 
//this should not compile, but lets assume it did.. 
foo_ptr(ptr); 
//Oh no, now ptr[0] is 'r' inside of constant memory, 
//but now since ptr isn't declared const here I can overwrite it! 
//But luckily most (all?) compilers actually fail to compile this code. 
ptr[0] = 'b'; 

但是,如果你改變你的參數,所以你不能影響指針指向的值,那麼編譯器會讓你在非const中過去,因爲沒有機會返回const值指針。

通過在參數減速後放置關鍵字const*就可以做到這一點。這意味着變化:

void foo_ptr(const char * & ptr) 

void foo_ptr(const char * const & ptr) 

和你的編譯器會很高興。

現在你不能在上面的例子中做類似ptr = "readonlystring"的事情,因爲那樣做現在永遠不會編譯。根據你的問題應該是可以的,因爲你不能在原始例子中對const char &進行分配。

+0

Eric和@詹姆斯的行爲:非常感謝你的傢伙。對我來說,這聽起來比任何其他人在這裏回答[至少對我的支持]。我是新手,如果可以在這裏添加一些帶有示例的解釋細節以幫助我們完全理解這些內容,那將非常有幫助。 (或者任何來源/鏈接也可以平等地工作)。 ....我特別想了一下「.... const數組指針,你有可能會返回一個const指針類型」......但是不能感到滿意......非常感謝您的時間和精力。 – anubhav16

+0

我用一些更多的代碼和解釋修改了答案。希望我添加的片段能夠解釋讓你困惑的線路,這將有所幫助。 – James

+0

太棒了..我現在明白了。非常感謝 :)。我感謝您花費的努力和時間。非常感謝。 – anubhav16

0

你不應該分配字符串文本到非constchar指針,你在這裏做的:

char *ptr = "anu";   

更改上述糾正代碼:

const char *ptr = "anu";   

...我想你會發現你的問題解決了。

+7

但是,這並不回答他的問題。 – Nawaz

+0

感謝的時候,卻是啊,這didnt回答我的問題。如果「常量」一直是唯一的關注,它是怎麼了foo_char工作? – anubhav16

10

假設你有

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?的簡歷版本。

+0

好一點。但你可以用'typedef char * CHARPTR'做到這一點 –

+1

不確定你的意思。將'char * ptr'改爲'CHAR PTR ptr'仍然會產生錯誤。 –

+0

什麼是錯誤?在OP代碼中替換'char *'w/typedef應該可以成功編譯。 –

相關問題