2014-01-08 84 views
-2

我在cocos2d的C++應用程序下面的代碼,但是代碼不編譯:C++ STD:字符串編譯錯誤

std::string MyBasketTimer::getImageByType(MyBasket* basket) { 
     std::string retVal=NULL; 
     if(getBasketType()==1){ 
      retVal= new std::string("count_bg.png"); 
     } 
     else if(getBasketType()==2){ 
      retVal= new std::string("count_bg.png"); 
     } 

     return retVal; 
    } 

的誤差得到的是

invalid conversion from 'std::string* {aka std::basic_string<char>*}' to 'char' [-fpermissive] 

我在做什麼錯誤?

+5

問題是,您正在嘗試編寫Java或C#,但在C++中。你應該選擇一個好的初學者的書,並開始閱讀。 – molbdnilo

+2

[這裏](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)是這樣的書的列表。 –

回答

-2

你的代碼將是正確的,如果該函數的返回類型是std::string *。例如

std::string * MyBasketTimer::getImageByType(MyBasket* basket) { 
     std::string *retVal=NULL; 
     if(getBasketType()==1){ 
      retVal= new std::string("count_bg.png"); 
     } 
     else if(getBasketType()==2){ 
      retVal= new std::string("count_bg.png"); 
     } 

     return retVal; 
    } 

但是你聲明的功能,使得它具有返回類型std::string。所以有效的功能實現將看起來如下

std::string MyBasketTimer::getImageByType(MyBasket* basket) { 
     std::string retVal; 
     if(getBasketType()==1){ 
      retVal.assign("count_bg.png"); 
     } 
     else if(getBasketType()==2){ 
      retVal.assign("count_bg.png"); 
     } 

     return retVal; 
    } 
+1

但調用者必須刪除第一種情況下的指針 – Bathsheba

+1

@Bathsheba什麼是問題? –

+7

@VladfromMoscow問題是這是一個脆弱的解決方案,OP將使用它而不是刪除它,然後抱怨C++需要GC等等。:-) – juanchopanza

3

轉讓std::string retVal = NULL;無效。只需默認使用std::string retVal;

也可以刪除new關鍵字,因爲它們在堆上創建對象並返回指向它們的指針。你需要,例如,retVal = std::string("count_bg.png");(這是C++和Java之間的一個重要區別)。

+0

+1,但可能值得指出'std :: string retVal = NULL;'會編譯,但在運行時會失敗。 – juanchopanza

3

在C++中(與其他一些語言不同),您不需要使用new分配所有類變量。只需分配它。

retVal= "count_bg.png";

4

你的返回類型爲std::string但你嘗試將指針賦給std::string它:

retVal= new std::string("count_bg.png"); 

您需要分配一個std::stringretVal

retVal = std::string("count_bg.png"); 

或者使用字符串文字的隱式轉換:

retVal = "count_bg.png"; 

而且,這種

std::string retVal=NULL; 

將最有可能導致運行時錯誤:你不能實例化一個空指針的字符串。這將調用std::string構造函數,其構造函數採用const char*,並假定它指向以空字符結尾的字符串。

+3

當然,這個答案是如此可怕地錯誤,它值得反對票:-) – juanchopanza

3

std::string retVal不是指針。你不能用NULL(它應該是nullptr ...)初始化它,也不能通過new分配內存分配的結果。

只是不初始化它,然後直接分配字符串。

std::string retVal; 
//... 
retVal = "count_bg.png" 
//... 
return retVal;