c++ - 我如何在函数cpp中返回字符串

标签 c++ string function compiler-errors return-value

我创建了一个读取JSON的函数以在OpenCV中设置屏幕,但是当它返回字符串时,会出现以下错误:

In member function ‘std::__cxx11::string JsonControl::GetJson(std::__cxx11::string)’:
/home/developer/Documents/Develloper/Kamino_Project/kamino_vizualization/modules/drivenet/src/json/read_json.cpp:27:1: error: control reaches end of non-void function [-Werror=return-type]
}

string JsonControl::GetJson(string getData)
{
   read_json("../modules/src/json/resources.json", root);

   BOOST_FOREACH (boost::property_tree::ptree::value_type &v, root.get_child(getData))
   {
       std::cout << v.second.data() << std::endl;

       stringstream geek(v.second.data());

       geek >> returnValue;

       return returnValue;
   }
}

string JsonControl::SetDataJson(string setData){
  returnValue = GetJson(setData);
  return returnValue;
}

非常感谢你....

最佳答案

问题在于BOOST_FOREACH是循环的一种,这意味着它将为匹配的树中的每个项目执行主体。由于它会返回匹配值,因此只有第一个会被操作。

但是,如果没有匹配项,则BOOST_FOREACH的主体将精确执行零次,因此循环内的return将永远不会执行。换句话说,它将从BOOST-FOREACH中掉出来,此时没有return语句将值返回给调用方。

要解决此问题,您可以根据需要抛出异常,或返回默认值,或其他任何数目的东西。例如,“默认值”选项可能类似于:

std::string JsonControl::GetJson(const std::string &key, const std::string &defaultVal) {
    read_json("../modules/src/json/resources.json", root);

    BOOST_FOREACH (boost::property_tree::ptree::value_type &v, root.get_child(getData)) {
        stringstream geek(v.second.data());
        geek >> returnValue;
        return returnValue;
    }

    return defaultValue;
}

关于c++ - 我如何在函数cpp中返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52539594/

相关文章:

c - 返回 char * 值

javascript - 调用具有多个参数的函数

c++ - Microsoft Build Tools 2013 缺少 v120 目录

c++ - 如何在 Windows 控制台中为特定像素着色

c++ - 使用 curl_easy_cleanup(curl) 时收到未处理的 NULL 异常

python-3.x - 从Python中的字符串中删除特殊字符

c++ - 从派生类数组读取访问冲突

python - 如何将字符串数组转换为字符串数组?

python - 用户警告 : Pandas doesn't allow columns to be created via a new attribute name -

python - 属性错误 : 'Foo' object has no attribute 'max'