我正在使用C++游戏教程,但无法弄清楚为什么我创建的类对象给我一个错误,即“表达式必须具有类类型”。该对象称为“menuEvent”,当您将鼠标悬停在变量上时,在摘要的第一行显示“sf::Event menuEvent”,但是在摘要的第二行显示“错误:表达式必须具有类类型”。在相同的摘要中它本身是矛盾的,我无法弄清楚。我正在使用C++代码在Visual Studio 2015中工作。任何帮助将不胜感激。这就是我所拥有的;
这一部分来自我的一个外部依赖文档。
namespace sf
{
class Event
{
public:
struct MouseButtonEvent
{
Mouse::Button button; ///< Code of the button that has been pressed
int x; ///< X position of the mouse pointer, relative to the left of the owner window
int y; ///< Y position of the mouse pointer, relative to the top of the owner window
};
};
}
然后,这是我的源文件之一;
MainMenu::MenuResult MainMenu::HandleClick(int x, int y)
{
std::list<MenuItem>::iterator it;
for (it = _menuItems.begin(); it != _menuItems.end(); it++)
{
sf::Rect<int> menuItemRect = (*it).rect;
if(menuItemRect.contains(sf::Vector2<int>(x,y)))
{
return it->action;
}
}
return Nothing;
}
MainMenu::MenuResult MainMenu::GetMenuResponse(sf::RenderWindow& window)
{
sf::Event menuEvent;
while (true)
{
window.pollEvent(menuEvent);
// The above line with menuEvent it reads as being of the sf::Event type
if (menuEvent.type == sf::Event::MouseButtonPressed)
{
//But the below line here when I hover over "menuEvent" it shows that it's of the sf::Event type, but then right below that it says "Error:expression must have class type".
return HandleClick(menuEvent.MouseButtonPressed.x , menuEvent.MouseButtonPressed.y);
}
if (menuEvent.type == sf::Event::Closed)
{
return Exit;
}
}
}
最佳答案
您声明了一个名为sf::Event
的类。
此类声明一个内部类MouseButtonEvent
。MouseButtonEvent
不是类成员。这是一个内部类(Class)。
您声明了一个名为“menuEvent”的sf::Event
实例:
sf::Event menuEvent;
您的编译器无法编译以下表达式:
HandleClick(menuEvent.MouseButtonPressed.x,
menuEvent.MouseButtonPressed.y);
该错误是因为
sf::Event
没有名为MouseButtonPressed
的类成员(从技术上讲,这不是完全正确的,但是我注意到该问题没有“language-lawyer”标签,因此我将其播放为“n-loose”。 ..)表达式“menuEvent.MouseButtonPressed”是对
menuEvent
的名为“MouseButtonPressed”的类的成员的引用。没有这样的类(class)成员。
MouseButtonPressed
是内部类,而不是类成员。您的代码意图对我而言并不明确,因此对于在此处试图完成的代码,我无法提出正确的语法。