我目前正在为大学项目开发一个简单的Scrabble实现。
不过,我无法参与其中!
看一下这个:
我的board.h:
http://pastebin.com/J9t8VvvB
错误所在的子例程:
//Following snippet contained in board.cpp
//I believe the function is self-explanatory...
//Pos is a struct containing a char, y, a int, x and an orientation, o, which is not //used in this particular case
void Board::showBoard()
{
Pos temp;
temp.o = 0;
for (temp.y = 'A'; temp.y < (65 + TOTAL_COLUMNS); ++temp.y)
{
for (temp.x = 1; temp-x < (1 + TOTAL_ROWS); ++temp.x)
{
cout << _matrix[temp].getContents();
}
cout << endl;
}
}
在编译时返回的错误:
http://pastebin.com/bZv7fggq
当我比较
char
和int
时,错误为何指出我要比较两个Pos?我也真的无法放置其他错误...
谢谢你的时间!
编辑:
由于我的整个项目都取决于Pos,因此我将尝试重载
最佳答案
#define TOTAL_ROWS 15;
#define TOTAL_COLUMNS 15;
这些是预处理程序定义,不能以分号结尾。分号将成为替换文本的一部分,因此编译器会看到类似
(65 + 15;)
的内容,这显然是错误的。在C++中,最好使用
const
变量而不是#define
。在这种情况下,您可以将以下内容放在Board.cpp
中:const unsigned int TOTAL_ROWS = 15;
const unsigned int TOTAL_COLUMNS = 15;
然后,可以通过将它们放在
Board.h
中,通过标题使它们可用:extern const unsigned int TOTAL_ROWS;
extern const unsigned int TOTAL_COLUMNS;
甚至更清洁的做法是将它们声明为类成员。将它们放在
Board.cpp
中:const unsigned int Board::TOTAL_ROWS = 15;
const unsigned int Board::TOTAL_COLUMNS = 15;
在
Board.hpp
定义的public
部分的class
中:static const unsigned int TOTAL_ROWS;
static const unsigned int TOTAL_COLUMNS;
它们必须是
static
,因为它们不属于任何特定的Board
实例,而是整个类的属性。然后,您可以通过编写Board
等从Board::TOTAL_ROWS
类外部访问它们。这里的另一个问题是您正在创建
map<Pos, Cell>
。 map
模板要求其键类型(Pos
)上定义了有效的<
运算符;在内部,map
使用此运算符对元素进行排序,因此可以进行快速查找。该错误仅在您尝试在 map 中查找内容时发生。这是由于模板的工作方式所致,所以请不要现在就动脑筋。一种解决方案是自己重载此运算符,以定义
Pos
对象的顺序。我不建议初学者这样做,因为map
星星会出现异常,而>
,<=
和>=
,==
和!=
。 就是说,这里是代码。假设两个
Pos
和x
值相同的y
对象被视为相等;它不会查看o
的值(无论如何,对于“坐标”类型来说这是很奇怪的事情,我不知道它的用途)。bool operator<(Pos const &l, Pos const &r) {
if (l.y < r.y) return true;
if (l.y > r.y) return false;
if (l.x < r.x) return true;
if (l.x > r.x) return false;
return false;
}
另一个(更好)的选择是完全放弃
Pos
类型,并将您的电路板表示为二维数组或vector
的vector
。然后,其类型为vector<vector<Cell> >
。 (请注意> >
之间的空格!如果没有空格,它将被解析为右移运算符>>
!)关于c++ - C++初学者-使用结构和常量会遇到麻烦!,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2812544/