所以我在完成一本介绍性的书之后尝试了一些C ++,然后我就陷入了困境。我已经创建了一个对象矢量,每个对象都有一个SFML圆对象作为成员,我希望main()去绘制这些圆。该向量称为theBoard
,但当我尝试访问它时,我收到以下错误消息:
error: request for member 'theBoard' in 'GameBoard', which is of non-class type 'Board*'
error: 'theBoard' was not declared in this scope
我是新手(来自两年的Python),所以我确定我在某处犯了一个错误。以下是创建电路板的相关代码:
class Board
{
public:
//These are the member functions.
Board();
~Board();
vector<Space*> CreateBoard();
//This will be the game board.
vector<Space*> theBoard;
//These clusters represent the waiting areas for pieces not yet in the game.
vector<Space*> Cluster1;
vector<Space*> Cluster2;
vector<Space*> Cluster3;
private:
//These integers represent the number of spaces on each row, starting at the top (which is row [0])
vector<int> RowNums;
};
Board::Board()
{
//Fill in RowNums with the right values.
RowNums.push_back(1);
RowNums.push_back(17);
RowNums.push_back(2);
RowNums.push_back(17);
RowNums.push_back(1);
RowNums.push_back(1);
RowNums.push_back(5);
RowNums.push_back(2);
RowNums.push_back(7);
RowNums.push_back(2);
RowNums.push_back(11);
RowNums.push_back(3);
RowNums.push_back(17);
RowNums.push_back(4);
RowNums.push_back(17);
//Then, create the board.
theBoard = CreateBoard();
}
CreateBoard()是一个非常非常长的函数,它返回一个指向Space对象的指针向量。我怀疑这里有一个问题,因为当我尝试访问main()中的Space对象的圆圈成员时,我得到的唯一错误信息。在我看来,好像我已在相关范围内声明theBoard
,即作为Board类的数据成员。
我的main()函数,如果它很重要:
int main()
{
//This sets up the display window.
sf::RenderWindow App(sf::VideoMode(1200, 900, 32), "Malefiz");
//This creates the board on the heap, and a pointer to it.
Board* GameBoard = new Board();
cout << "Board made.";
//This is the game loop.
while(App.IsOpened())
{
//This is used to poll events.
sf::Event Event;
while(App.GetEvent(Event))
{
//This closes the window.
if(Event.Type == sf::Event::Closed)
{
App.Close();
}
}
//This gets the time since the last frame.
//float ElapsedTime = App.GetFrameTime();
//This fills the window with black.
App.Clear(sf::Color(200, 200, 125));
//This draws the places into the window.
for(int i = 0; i < GameBoard.theBoard.size(); ++i)
{
App.Draw(GameBoard.*theBoard[i].m_Circle);
}
//This displays the window.
App.Display();
}
return EXIT_SUCCESS;
}
答案 0 :(得分:6)
在main()
函数中,GameBoard
是Board *
,而不是Board
。因此,要访问成员,您需要使用->
而不是.
。 e.g:
GameBoard->theBoard.size()
[有些人(我就是其中之一)喜欢用前导p
或ptr
前缀来命名他们的指针变量,以便明确地明白这种烦恼。< / EM>
答案 1 :(得分:4)
GameBoard是指向Board对象的指针,因此您需要使用“ - &gt;”运算符而不是“。”运算符访问其任何成员变量或方法。
答案 2 :(得分:3)
GameBoard
是一个指针,所以语法应为:
for(int i = 0; i < GameBoard->theBoard.size(); ++i)
{
App.Draw((GameBoard->theBoard[i])->m_Circle);
}
由于theBoard
的元素也是指针,所以在访问m_Circle
时我使用了指针符号。
答案 3 :(得分:3)
如果你仔细阅读,错误是非常明确的:
error: request for member 'theBoard' in 'GameBoard', which is of non-class type 'Board*'
error: 'theBoard' was not declared in this scope
第一行告诉您,您有一个指向Board
对象的指针,并且您正在尝试直接访问成员。那就是:
Board *p = ...
p.theBoard; // Error, should be p->theBoard, as p is a pointer
另请注意,GameBoard.*theBoard[i].m_Circle
可能不是您想要的,您可能想要(我猜是因为缺少重要的部分),例如GameBoard->theBoard[i]->m_Circle
。