错误:“需要一个类型说明符”

RDK*_*har 0 c++ struct sfml

我收到此错误,但在尝试创建新对象指针时不知道为什么。

这是我的头类的代码

#ifndef CURSOR_H_INCLUDED
#define CURSOR_H_INCLUDED
#include <SFML\Graphics.hpp>
#Include "Mango.h"
#include <stack>

using namespace sf;
using namespace std;

struct cursor{
 Texture tCursor;
 Sprite sCursor;
 stack<Mango*> inv;
 float money;
 void Sell();
 cursor();
 ~cursor();
};

#endif CURSOR_H_INCLUDED
Run Code Online (Sandbox Code Playgroud)

主要是尝试这样做

cursor * cursor = new cursor();
Run Code Online (Sandbox Code Playgroud)

但它给了我那个错误。

Zeb*_*ish 5

您已将指针命名为与类名相同的名称。你不能这样做:

struct Foo {int a;};

int main()
{
        Foo* Foo = new Foo(); // Because
// After here ^^^ Foo is no longer a type but a variable. And you can't "new"
// a variable. Thanks to user4581301 for teaching me this.

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在:

cursor * cursor = new cursor();
         ^^^^^^
Run Code Online (Sandbox Code Playgroud)

将指针名称从光标更改为其他名称。

PS 有趣的是,感谢 user4581301 我知道变量可以与用户定义的类型同名,但这显然是个坏主意。所以:

Foo Foo; // Fine
Foo.a = 7; // Fine
Foo newFooObj; // Doesn't make sense, Foo is no longer seen as a type 
Run Code Online (Sandbox Code Playgroud)