0

我一直在尝试将一个包含我所有变量的结构传递给多个函数,这些函数保存在一个单独的类中。我知道这个错误很可能与某种语法错误有关,但我看不出我做错了什么。

main.ccp 是:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include "running.h"

using namespace std;

int main()
{
    //------Class Objects---------
    running runObj;

    //----------Vars--------------

    char saveGame = 'N';
    struct gameVar
    {
        int correctGuesses;  // These vars need to be reset for each new game.
        int Lives;
        int rowCorrect;
        int highScore;
        char anotherGame;
    } values;
    values.highScore = 12;
    values.anotherGame = 'Y';

    //--------Game Loop-----------

    // int highScore2 = runObj.readHighScore();


    while (values.anotherGame = 'Y')
    {
        struct gameVar = runObj.processGame(gameVar);
        struct gameVar = runObj.afterText(gameVar);
        gameVar values;
        values.anotherGame;
    }


    cout << endl << "-------------------------------------------------------" << endl;
    cout << "Would you like to save your high score? Y/N" << endl;
    cin >> saveGame;

    if(saveGame == 'Y')
    {
        runObj.saveHighScore(gameVar);
    }

    return 0;
}

我的头文件是:

#ifndef RUNNING_H
#define RUNNING_H


class running
{
    public:
        struct gameVar processGame(struct gameVar);
        void saveHighScore(struct hs);
        int readHighScore();
        struct gameVar afterText(struct gameVar);
};

#endif // RUNNING_H
4

1 回答 1

1

首先,一个简单的问题:您=while循环条件中使用,这会将值分配'Y'gameVar.anotherGame. 你真正想要的是==,测试平等。

看看这一行:

struct gameVar = runObj.processGame(gameVar);

你想在这里做什么?gameVar是您的结构的名称,而不是gameVar类型的对象。您的对象实际上被称为values. 也许您想做类似的事情:

values = runObj.processGame(values);

下一行也是如此。

看起来你有这种困惑的原因是因为你在定义你struct的同时创建了一个该类型的对象。被struct调用gameVar的只是对象的蓝图,您创建一个与该蓝图匹配的对象,称为values

struct gameVar
{
  // ...
} values;

如果struct将函数外部定义main为:

struct gameVar
{
  // ...
};

然后使用以下命令创建它的实例main

gameVar values;

您必须将这个values对象传递给函数 - 您不能传递类型,这就是gameVar

我不确定你当时试图做什么:

gameVar values;
values.anotherGame;

这将重新定义循环内的values对象,while并将在循环结束时销毁。然后您访问数据成员anotherGame,但不对其执行任何操作。也许您正在寻找:

gameVar values;
values.highScore = 12;
values.anotherGame = 'Y';

while (values.anotherGame == 'Y')
{
    values = runObj.processGame(values);
    values = runObj.afterText(values);
}

值得注意的是,在 C++ 中,您不需要struct在每次使用之前放置gameVar类型。类型名称只是gameVar. 也就是说,您可以将声明更改processGame为:gameVar processGame(gameVar);

于 2013-02-08T20:57:30.573 回答