2014-01-08 46 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;