C++ 错误:[函数名] 之前的预期初始化程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14321930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C ++ error: a expected initializer before [function name]
提问by WorkerBee
I am refreshing my self on C++ (have not did it since school) and I wrote a simple program just to mess around. My problem is when I compile the program it chokes stating "error: expected initializer before 'stringThing'" is there a reason why this is doing this? I know this may be a noob question so I checked stackoverflow and could not find any relevant questions that gave me a answer.
我正在用 C++ 更新我的自我(从学校开始就没有这样做过),我写了一个简单的程序只是为了捣乱。我的问题是,当我编译程序时,它会提示“错误:'stringThing' 之前的预期初始化程序”是否有这样做的原因?我知道这可能是一个菜鸟问题,所以我检查了 stackoverflow 并找不到任何给我答案的相关问题。
*I am using GNU GCC compiler
*我正在使用 GNU GCC 编译器
Code:
代码:
#include <iostream>
using namespace std;
void string stringThing (string shiftdir, string &teststring)
{
if (shiftdir == "right")
{
teststring = teststring >> " " >> "Bit Shifted right";
}
else
{
teststring = teststring << " " << "Bit Shifted left";
}
}
int main()
{
string test;
cout << stringThing("right", "I have done a ") << endl;
return 0;
}
采纳答案by Olaf Dietsche
The return type for stringThing
must be either void
orstring
, not both. You also must include <string>
, if you want to use string.
的返回类型stringThing
必须是void
或string
,而不是两者。<string>
如果要使用字符串,还必须包含。
Since you want to output the return value of stringThing()
in main
, I guess it should be
既然要输出stringThing()
in的返回值main
,我想应该是
std::string stringThing (std::string shiftdir, const std::string &teststring)
But then, you must also return a string from your function
但是,您还必须从函数中返回一个字符串
if (shiftdir == "right")
return teststring + " " + "Bit Shifted right";
else
return teststring + " " + "Bit Shifted left";
for example.
例如。
Your parameter std::string &teststring
won't work with your const char*
argument. So either declare it as a copy by value string
only, or better const string&
.
您的参数std::string &teststring
不适用于您的const char*
参数。因此,要么string
仅按值将其声明为副本,要么更好const string&
。
回答by Lightness Races in Orbit
Return type is … funky
返回类型是……时髦
What is:
什么是:
void string stringThing (string shiftdir, string &teststring)
?
?
Get rid of the first string
. Your function returns nothing.
摆脱第一个string
。您的函数不返回任何内容。
So, simply:
所以,简单地说:
void stringThing(string shiftdir, string &teststring)
Inclusion missing
包含缺失
You will also need to #include <string>
— in some scenarios you may get "lucky" and have it implicitly included by <iostream>
, but don't rely on it.
您还需要#include <string>
- 在某些情况下,您可能会“幸运”并将其隐式包含在 中<iostream>
,但不要依赖它。