返回字符串;没有花括号就无法工作

return string; not working without curly brackets

本文关键字:工作 字符串 返回      更新时间:2023-10-16

这是我在.h文件中的函数:

static std::string ReturnString(std::string some_string)
    return ("t<" + some_string + " ");

编译器(g++-std=c++0x-pedantic-Wall-Wextra)抛出以下错误:

error:expected identifier before '(' token
error:named return values are no longer supported
error:expected '{' at end of input
warning: no return statement in function returning non-void [-Wreturn-type]

但是,

static std::string ReturnString(std::string some_string)
{
    return ("t<" + some_string + " ");
}

工作良好。偶数,

static std::string ReturnString(std::string some_string)
{
    return "t<" + some_string + " ";
}

同样有效。

有人能给我解释一下吗?我是不是错过了一些弦的基本知识?

谢谢。

static std::string ReturnString(std::string some_string)
    return ("t<" + some_string + " ");

这实际上是您所缺少的C++的基本知识。在C++中,函数体必须用大括号{}括起来。因此,上面函数的正确定义是:

static std::string ReturnString(std::string some_string)
{
    return ("t<" + some_string + " ");
}

这与字符串无关。这是关于你如何定义你的功能。在这种情况下,ReturnString是一个返回字符串的函数。

C++函数定义的通用格式为:

ReturnType NameOfTheFunction(Parameters)
{
    Implementation
}