我有一个结构和两个函数,在其中一个函数中我使用结构来执行一些检查,我想在另一个函数中调用该函数,所以当在该函数中采取某些动作时,另一个可以做检查。假设对象球上升,在进行另一次移动之前执行检查。我知道你可以在另一个函数中调用函数,但是我不能像我用变量int调用其他函数那样调用它,例如,我想因为结构。如何在显示功能中调用该检查功能?提前谢谢!
struct box{
//code
};
void checker(box A, box B, box C, box D, box E, box Q){
/*Creating struct of type boxes here and statements to cheack if any of the limits between them intersect each other*/
}
void display(){
//Displaying the objects here that are inside the structure box to check collision
}
答案 0 :(得分:1)
喜欢这个吗?
void display()
{
box A, B, C, D, E, Q;
// ...
checker(A, B, C, D, E, Q);
// ...
}
答案 1 :(得分:1)
你想知道如何传递参数吗?
你似乎是C ++的新手。您可能想要阅读一些关于功能的内容。
struct box{
//code
}; //forgot semicolon
void checker(box A, box B, box C, box D, box E, box Q){
//code
}
void display() //forgot parenthesis
{
box A, B, C, D, E, Q;
//initialize and use variables.
//call function...
checker(A, B, C, D, E, Q);
}
很难说出你究竟在问什么。
一个想法。
也许你想要这样的东西(在这里大肆宣传。主要是向你展示一个场景。):
class Box
{
//code
};
class GameState
{
public:
GameState(map<std::string, Box> _boxes);
void display();
void moveBox(std::string boxID, int x, int y);
private:
bool checkMove(std::string boxID, int x, int y);
std::map<std::string, Box> boxes;
};
void mainLoop()
{
map<string, Box> boxes;
boxes["A"] = Box();
boxes["B"] = Box();
boxes["C"] = Box();
boxes["D"] = Box();
boxes["E"] = Box();
boxes["Q"] = Box();
bool quit = false;
GameState game(boxes);
while(true)
{
int action = game.getAction();
switch(action)
{
case DISPLAY_ACTION:
game.display();
break;
case MOVE_ACTION:
string boxId;
int x, y;
//get those somehow...
game.moveBox(boxId, x, y);
break;
case QUIT;
quit = true;
break;
}
if (quit)
break;
}
}
int GameState::getAction(box& aBox)
{
//return some action code
}
bool GameState::checkMove(string boxId, int x, y)
{
//check box
}
void GameState::display()
{
}
void GameState::moveBox(string boxId, int x, int y)
{
if (checkMove(boxId, x, y))
{
//more code
}
}
答案 2 :(得分:0)
首先,显示功能的原型缺少其参数:
void display(/* parameters here if needed */) {
//I want to call the void checker here
}
关于你的问题,调用函数是一件微不足道的事情。例如,使用不带任何参数的显示功能:
void display() {
// have some boxes defined here
Box ba,bb,bc,bd,be,bq;
// here we have some code related to the boxes
// (...)
// (...)
// and now we call the function checker
checker(ba,bb,bc,cd,be,bq);
}
但是,您似乎还希望在checker
中创建框的内容,然后在display
中显示它们。为此,您需要将Box对象通过引用传递给checker
,以便在退出函数时该函数所做的任何修改都会保留。
因此,您需要将检查器的原型更改为:
void checker(box &A, box &B, box &C, box &D, box &E, box &Q){
/* your function body here */
}
答案 3 :(得分:0)
您需要更详细地澄清您的问题。但从上下文来看,这表明你正在尝试做以下事情:
每个对象都由此结构表示:
struct box { };
您有一个显示游戏状态(布局)的显示功能。
您希望在显示之前检查是否存在碰撞。
如果您正在尝试实现以上目标,则可以执行以下操作:
class Game {
public:
Game() {} // Initialize your box objects here
~Game() {}
void display() {
// Your code
checker(a_, b_); // Check here
// Display code
}
private:
struct Box {
// box state data
};
Box a_;
Box b_;
// ... etc.
void checker(const Box& a, const Box& b) const {
// Do your check here
// I used const here assuming your checker has no side effects
}
};