C ++ 错误:[函数名称] 之前的预期初始化程序

Wor*_*Bee 7 c++ gcc compiler-errors

我正在用 C++ 更新我的自我(从学校开始就没有这样做过),我写了一个简单的程序只是为了捣乱。我的问题是,当我编译程序时,它会提示“错误:'stringThing' 之前的预期初始化程序”是否有这样做的原因?我知道这可能是一个菜鸟问题,所以我检查了 stackoverflow 并找不到任何给我答案的相关问题。

*我正在使用 GNU GCC 编译器

代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Ola*_*che 5

的返回类型stringThing必须是void string,而不是两者。<string>如果要使用字符串,还必须包含。

既然要输出stringThing()in的返回值main,我想应该是

std::string stringThing (std::string shiftdir, const std::string &teststring)
Run Code Online (Sandbox Code Playgroud)

但是,您还必须从函数中返回一个字符串

if (shiftdir == "right")
    return teststring + " " + "Bit Shifted right";
else
    return teststring + " " + "Bit Shifted left";
Run Code Online (Sandbox Code Playgroud)

例如。

您的参数std::string &teststring不适用于您的const char*参数。因此,要么string仅按值将其声明为副本,要么更好const string&