无法将指针定义为用户定义的类,但我可以直接实例化

Cannot make a pointer to user defined class but i can directly instantiate it

本文关键字:定义 我可以 实例化 指针 用户      更新时间:2023-10-16

我有一个名为hud的类,每当我写

HUD *hud = new HUD(screenwidth,screenHight);

我得到此错误

缺少类型指定符 - 假定的int。注意:C 不支持Default-Int

但是,如果我直接实例化

Hud hud(screenwidth,screenHight);

它可以正常工作,我该如何解决此问题这是代码的CPP

HUD::HUD(float windowWidth,float windowHeight){
    sf::Font font;
    font.loadFromFile("arial.ttf");
    time.setFont(font);
    time.setColor(Color::White);
    time.setPosition(Vector2f(windowWidth/2,VERTICAL_INDENTATION));
    time.setCharacterSize(FONT_SIZE);
    coinIcon.loadFromFile(COIN_ICON);
    coinDisplay.setTexture(&coinIcon);
    coinDisplay.setSize(Vector2f(20,20));
    coinDisplay.setPosition(Vector2f(0,VERTICAL_INDENTATION));
    coins.setFont(font);
    coins.setColor(Color::White);
    coins.setPosition(Vector2f(HORIZONTAL_INDENTATION,VERTICAL_INDENTATION));
    coins.setCharacterSize(FONT_SIZE);
    numOfCoins = 0;
}

void HUD::startClock(){
    clock.restart();
}
// returns seconds to the nearest digit
int HUD::getTimeElapsed(){
    return (int)(0.5+clock.getElapsedTime().asSeconds());
}
void HUD::incrementCoins(){
    numOfCoins++;
}
int HUD::getNumOfCoins(){
    return numOfCoins;
}
// only accepts positive numbers
std::string HUD::toString(int num){
    std::string str("");
    char digit;
    while(num%10 != 0){
        digit = '0'+num%10;
        str.insert(0,1,digit);
        num /= 10;
    }
    if(str.size() == 0)
        str = "0";
    return str;
}
void HUD::render(RenderWindow *window){
    coins.setString(toString(numOfCoins));
    time.setString(toString((int)(0.5+clock.getElapsedTime().asSeconds())));
    window->draw(coinDisplay);
    window->draw(coins);
    window->draw(time);
}

这是标题文件

using namespace sf;
#define COIN_ICON "Textures/coin.png"
#define VERTICAL_INDENTATION 20
#define HORIZONTAL_INDENTATION 20
#define FONT_SIZE 30
class HUD{
    RectangleShape coinDisplay;
    Texture coinIcon;
    Text coins;
    int numOfCoins;
    sf::Clock clock;
    Text time;
    std::string toString(int num);
public:
    HUD(float windowWidth,float windowHeight);
    ~HUD(void);
    void startClock();
    int restartClock();
    void render(RenderWindow *window);
    int getTimeElapsed();
    void incrementCoins();
    int getNumOfCoins();
};

您无法制作指针,因为您不要求一个。

您要寻找的语法是:

HUD* hud = new HUD(screenwidth,screenHight);

那和:

之间的区别
HUD hud;

是前者在堆上实例化对象,而后者则在堆栈上实例化对象。您必须确保致电:

delete hud;

如果您选择使用第一个方法实例化。

声明指针的正确语法是:

HUD* hud = new HUD(screenwidth,screenHight);

但是,您不应在可能的情况下使用裸指针。阅读此。

编辑

我注意到您写道,当您将类型声明为Hud而不是HUD时,它有效。我怀疑这里有一个错字。

找到了问题的来源。问题在于,在项目中,我使用了一个名为Common的标题,该标题包括项目中的所有标题,并包括每个CPP文件中的共同点。由于某种原因,即使包括HUD包括共同的共同点,它仍然无法使用,直到我将HUD.H纳入标头文件中,宣布指针HUD

相关文章: