【问题标题】:return string; not working without curly brackets返回字符串;没有大括号就不能工作
【发布时间】:2013-07-12 11:51:44
【问题描述】:

这是我在 .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 + " ";
}

也可以。

有人可以向我解释一下吗?我是否缺少一些字符串的基本知识?

谢谢。

【问题讨论】:

  • 只是函数的基本知识:你总是必须用花括号将函数体括起来,即使它只有一行长。就是这样。

标签: c++ xml string curly-brackets


【解决方案1】:
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 + " ");
}

【讨论】:

  • 啊!谢谢。尴尬的。之前在同一行中使用 {} 完成了一行功能,只是进入第二行让我忘记了括号。
【解决方案2】:

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

C++ 函数定义的一般格式为:

ReturnType NameOfTheFunction(Parameters)
{
    Implementation
}

【讨论】:

  • auto NameOfTheFunction(Parameters) -&gt; ReturnType { Implementation }
  • 或很快auto Name(Parameter) { return /* something */; }; :)
  • 最后一个分号不是必须的吧?但这是标准做法吗?
猜你喜欢
  • 1970-01-01
  • 2014-09-29
  • 2015-02-09
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
  • 2022-11-18
  • 2010-12-02
相关资源
最近更新 更多