2013-02-08 305 views
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 

回答

1

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

看看这一行:

struct gameVar = runObj.processGame(gameVar); 

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

values = runObj.processGame(values); 

同样也是下一行。

看起来你有这种困惑的原因是因为你在创建该类型的对象的同时定义了你的struct。该struct称为gameVar仅仅是对象的蓝图,并且建立了该蓝图称为values匹配的对象:

struct gameVar 
{ 
    // ... 
}; 

struct gameVar 
{ 
    // ... 
} values; 

,如果你定义structmain功能外,你可能不太糊涂

然后在main创建它的实例与:

gameVar values; 

这个values对象,你必须传递给一个函数 - 你不能传递一个类型,这是什么gameVar是。

我不知道你随后尝试与做:

gameVar values; 
values.anotherGame; 

这将重新定义循环while内的values对象,它会在循环的末尾被销毁。然后访问数据成员anotherGame,但不要对它做任何事情。也许你正在寻找:

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

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

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

+0

谢谢您的帮助!我认为我现在对结构有更加坚定的把握,现在结构正在工作。再次感谢你! – ponger3d 2013-02-08 21:20:42

相关问题