函数参数中的引用

Reference at the function parameter

本文关键字:引用 参数 函数      更新时间:2023-10-16
嗨,我

目前正在学习如何在 c++ 中实现状态机,但我真的不明白我用以下代码为我的函数提供了什么:

void promptfornextevent(elevatorstate& state, int event){
   std::cout<<"Current State = "<< state.Description() << std::endl;
}

我在主函数中这样称呼它:

int main(){
...
elevatorstate* currentstate = new state_1stfloor;
promptfornextevent(*currentstate, event);
...
}

我不明白在电梯状态和状态线上使用参考的观点。我的函数究竟从主函数接收什么?我以为我给我的函数一个对象(由当前状态指向)

首先,通过引用传递参数,可以避免创建参数的额外副本。引用指向在 main 函数中创建的同一对象。

如果通过 copy 传递参数,则会调用 elevatorstate 的复制构造函数,并将返回值分配给state参数。

由于在 promptfornextevent 函数中使用相同的对象,因此即使您返回到 main 函数,在 promptfornextevent 中对对象所做的任何更改都将保留。