在函数之间传递变量不起作用

时间:2016-04-20 08:08:37

标签: c++11

我是c ++的新手,现在正在修读课程。

我编码公牛和奶牛猜我的文字游戏。

我完成了代码,但它没有按照我想要的方式工作。

当我尝试在两个函数之间传递变量时失败。

那就是代码:

 #include <iostream>
#include <string>

using namespace std;

void PrintIntro();         <-- the function that passes the variable
void PlayGame();           <-- the function trying to get the vriable
string PlayersGuess();

int main()
{
    // Printing the Intro and Instrations of the game
    PrintIntro();
    // Function to play our game
    PlayGame();

    return 0; // exits the application
}

    void PrintIntro()
    {
        // introduce the game
        constexpr int WORD_LENGTH = 5;
        cout << "Welcome to Bulls and Cows" << endl;
        cout << "Can you guess the " << WORD_LENGTH << " letter word I'm thinking of?" << endl;
        cout << endl;
        PlayGame(WORD_LENGTH);        <-- Taking the variable
        return;
    }

    string PlayersGuess()
    {
        // get a guess from the player
        cout << "Enter your guess: ";
        string Guess = "";
        getline(cin, Guess);
        cout << endl;
        return Guess;
    }

    void PlayGame(const int &passed)    <-- passing through here
    {
        // Game Intro
        for (int i = 0; i < passed; i++)     <-- to here
        {
            // Players Guess
            string Guess = PlayersGuess();
            cout << "Your guess is: " << PlayersGuess() << endl;
            cout << endl;
        }
    }

结果是失败,它说“功能不带1个参数”

传递它的正确方法是什么?

4 个答案:

答案 0 :(得分:1)

更改声明:

void PlayGame()

要:

void PlayGame(const int &passed)

答案 1 :(得分:1)

声明无效PlayGame();在开始时不接受参数。将声明更改为接受所需类型的参数。声明和定义必须匹配。希望这会有所帮助。

答案 2 :(得分:0)

函数声明和定义的签名必须相互匹配。你需要声明这样的函数:

void PlayGame(const int &passed);

在您的代码中,您有两个名为PlayGame的不同功能。在使用参数调用PlayGame()时,编译器尚未满足相应的函数,因此它会给出错误。

答案 3 :(得分:0)

如果你想让一个函数接受一个参数,你必须告诉编译器它需要一个参数。

函数原型声明

void PlayGame();

告诉编译器PlayGame函数接受 no 参数,并且不返回任何值。如果您尝试使用与声明不匹配的参数调用它,则会出现错误。

另一方面,如果你声明它就像你的定义:

void PlayGame(const int &passed);

然后你告诉编译器函数必须接受一个参数(对常量int的引用),并且你不能在没有参数的情况下调用该函数。

如果你想要不同的行为,取决于传递的参数(或缺少),那么你有两个解决方案:函数重载或默认参数。

例如,你可以有两个不同的函数,它们具有相同的名称,但不同的签名(基本上是不同的参数),所以你可以有例如。

void PlayGame() { ... }
void PlayGame(int passed) { ... }

然后(使用正确的前向声明)你可以使用无参数调用它,在这种情况下将调用第一个函数,或者使用整数值,在这种情况下将调用第二个函数。

使用默认参数可以执行类似

的操作
void PlayGame(int passed = 0) { ... }

然后,如果使用参数调用该函数将传递参数,如果您在没有任何参数的情况下传递它,则将使用默认值(在我的示例中为0)。

另请注意,我删除了常量引用部分,这对于简单的int值并不是真正需要的。

所有这一切都应在any good book中明确说明。