簡體   English   中英

C ++,在類vars中添加條件語句

[英]C++, Adding conditional statements in class vars

抱歉,但是我必須重復在“ C ++,在類vars中添加條件 ”之前問過的相同問題。

我在這里使用SDL2。

在obj.h中:(不包括預處理程序命令)

class obj {
public:
        SDL_Rect clip;
        void addCollideWith( SDL_Rect rect );
        void hasCollide();
        void clearCollideWith();
private:
        std::list<bool *> collideWith;
};

在obj.cpp中:(不包括預處理程序命令)

void obj::addCollideWith( SDL_Rect rect )
{
        collideWith.push_back(SDL_HasIntersection(obj.clip, rect));
}

void obj::hasCollide()
{
    bool retval = true;
    for (std::list<bool *>::iterator it = collideWith.begin(); it != collideWith.end(); it++) 
    {
        retval = retval && **it;
    }
    return retval;
}

void clearCollideWith()
{
    collideWith.clear();
}

在main函數內部,我說的是對象移動一個像素,每移動一個像素,它就會檢查是否與其他對象發生碰撞。 我清除了指針內容'*',因為我沒有放入變量,如您所見: collideWith.push_back(SDL_HasIntersection(obj.clip, rect)); 我要做的是使它移動一個像素,清除collideWith並再次添加collideWith條件以更新它是true還是false。

現在,出什么問題了?

這使得程序真的很慢! 如果我刪除collideWith東西,然后啟動程序,它將變得更加流暢。 現在,我想要的是存儲語句,而不是true或false。 std::list需要:

collideWith.pushBack(true /*OR*/ false);

但是我想要的是:

collideWith.pushBack(/*statement determining whether it is true or false*/ var1 > var2);

如果上下文缺失或問題是某種原因,無法理解,請不要抱怨! (注意:未提及與移動對象和聲明obj clip sub-vars有關的上下文,因為它們不是問題的一部分。)

您可以嘗試更換

    std::list<bool *> collideWith;

    std::list<SDL_Rect> collideWith;

為了跟蹤您要考慮的矩形。

實現可以是:

void obj::addCollideWith( SDL_Rect rect )
{
        collideWith.push_back(rect);
}

// to test if it collides with at least one rectangle
bool obj::hasCollide()
{
    bool retval = false;
    for (std::list<SDL_Rect>::iterator it = collideWith.begin(); it != collideWith.end(); it++) 
    {
        retval = retval || SDL_HasIntersection(obj.clip, *it);
    }
    return retval;
}

// to test if it collides with all rectangles
/* bool obj::hasCollide()
{
    bool retval = true;
    for (std::list<SDL_Rect>::iterator it = collideWith.begin(); it != collideWith.end(); it++) 
    {
        retval = retval && SDL_HasIntersection(obj.clip, *it);
    }
    return retval;
} */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM