C++标准:字符串编译错误

C++ std:string compilation error

本文关键字:编译 错误 字符串 标准 C++      更新时间:2023-10-16

我的 cocos2d C++应用程序中有以下代码,但代码没有编译:

  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]

我做错了什么?

您的返回类型是std::string,但您正在尝试分配指向它的指针std::string

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

您需要为retVal分配一个std::string

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

或者使用字符串文本的隐式转换:

retVal = "count_bg.png";

此外,这

std::string retVal=NULL;

很可能会导致运行时错误:不能使用 NULL 指针实例化字符串。这将调用接受const char*std::string构造函数,并假定指向一个以空值结尾的字符串。

std::string retVal = NULL;无效。只是默认使用std::string retVal;构造它

此外,在堆上创建对象时删除new关键字并返回指向它们的指针。例如,您需要retVal = std::string("count_bg.png");(这是C++和Java之间的一个重要区别)。

在C++中(与其他一些语言不同),您不需要使用 new 分配所有类变量。只需分配它。

retVal= "count_bg.png";

std::string retVal不是

指针。您不能用NULL初始化它(应该nullptr...),也不能通过new分配内存分配的结果。

只是不要初始化它并直接分配字符串。

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

如果函数的返回类型为 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;
    }