C++,在类变量中添加条件语句

C++, Adding conditional statements in class vars

本文关键字:添加 条件 语句 类变量 C++      更新时间:2023-10-16

抱歉,但我必须重复我之前提出的相同问题"C++,在类变量中添加条件"。

我在这里使用 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));.我所做的是让它移动一个像素,清除碰撞并再次添加碰撞条件以更新它是真的还是假的。

现在,问题出在哪里?

它使程序真的很慢!如果我删除碰撞的东西,然后启动程序,它会变得更加流畅。现在,我想要的是存储语句,而不是真或假。 std::list需要:

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

但我想要的是:

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

如果上下文缺失或问题以某种方式无法理解,请投诉!(注意:未提及与移动对象和声明 obj clip 子变量相关的上下文,因为它们不是问题的一部分。

您可以尝试替换

    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;
} */