C ++初学者 - 在类中使用类时遇到麻烦

时间:2010-05-10 15:27:39

标签: c++ class header-files return-type

我正在开展一个大学项目,我必须在那里实施一个简单的Scrabble游戏。

我有一个player课程(包含分数和玩家的手,形式为std::stringscore类(包含姓名和数字({{1}得分)。

int的一个成员函数是Player,它返回该玩家的Score对象。但是,我在编译时遇到以下错误:

Score getScore()

分别是第27行和第35行:

player.h(27) : error C2146: syntax error : missing ';' before identifier 'getScore'
player.h(27) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
player.h(27) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
player.h(27) : warning C4183: 'getScore': missing return type; assumed to be a member function returning 'int'
player.h(35) : error C2146: syntax error : missing ';' before identifier '_score'
player.h(35) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
player.h(35) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

我知道编译器无法将Score getScore(); //defined as public (...) Score _score; //defined as private 识别为有效类型......但为什么呢?我在Score的开头正确添加了Score.h

player.h

我在#include "Score.h" #include "Deck.h" #include <string> 中定义了Score的默认构造函数:

Score.h

任何意见都会受到赞赏!

感谢您的时间,

旧金山

编辑:

根据要求,score.h和player.h: http://pastebin.com/3JzXP36i http://pastebin.com/y7sGVZ4A

3 个答案:

答案 0 :(得分:7)

你有一个循环包含问题 - 在这种情况下相对容易修复。

#include "Player.h"删除Score.h


请参阅this问题,了解Score实际使用Player时您需要做什么的解释和讨论。


至于你得到的编译器错误,这就是微软的编译器如何报告未定义类型的使用 - 你应该学会将它们全部精神上翻译成“未定义的声明中使用的类型”。

答案 1 :(得分:3)

您的问题是递归包含Score.h正在尝试包含Player.h,而Player.h正在尝试包含Score.h。由于Score类似乎实际上并未使用Player类,因此从#include "Player.h"中删除Score.h可以解决您的问题。

答案 2 :(得分:1)

您有circular dependency problemScore.h包括Player.hPlayer.h包含Score.h

要解决此问题,请将您的包含内容删除到Player.h中的Score.h,如果需要在Score类中使用,请定义class Player;