C/C++函数参数传递机制详解及实例

 更新时间:2020年4月25日 17:32  点击:1983

C/C++函数参数传递机制详解及实例

概要:

C/C++的基本参数传递机制有两种:值传递和引用传递,我们分别来看一下这两种的区别。

(1)值传递过程中,需在堆栈中开辟内存空间以存放由主调函数放进来的实参的值,从而成为了实参的一个副本。值传递的特点是被调函数对形参的任何操作都是作为局部变量进行,不会影响主调函数的实参变量的值。

(2)引用传递过程中,被调函数的形参虽然也作为局部变量在堆栈中开辟了内存空间,但是这时存放的是由主调函数放进来的实参变量的地址。被调函数对形参的任何操作都被处理成间接寻址,即通过堆栈中存放的地址访问主调函数中的实参变量。正因为如此,被调函数对形参做的任何操作都影响了主调函数中的实参变量。

下面我们来看一个示例。

/*
*测试函数参数传递机制
*/
class CRect {

public:
  int height;
  int widht;

  CRect() {
    height = 0;
    widht = 0;
  }

  CRect(int height, int widht) {
    this->height = height;
    this->widht = widht;
  }

};

//(1)传址调用(传指针)
int RectAreaPoint(CRect *rect) {
  int result = rect->height * rect->widht;
  rect->height = 20;
  return result;
}

//(2)引用传递
int RectAreaRefer(CRect &rect) {
  int result = rect.height * rect.widht;
  rect.height = 30;
  return result;

}

//(3)传值调用
int RectArea(CRect rect) {
  int result = rect.height * rect.widht;
  rect.height = 40;
  return result;
}

看一下我们的测试代码和测试结果。

//测试代码逻辑
void testPoint() {
  CRect rect(10, 10);
  cout << "面积:" << RectAreaPoint(&rect) << endl;
  cout << "面积:" << RectAreaRefer(rect) << endl;
  cout << "rect.height:" << rect.height << endl;
  cout << "面积:" << RectArea(rect) << endl;
  cout << "rect.height:" << rect.height << endl;
}

//测试结果
面积:100
面积:200
rect.height:30
面积:300
rect.height:30

可以发现传址调用和引用传递两种方式,当改变形参的值时,同时也会将实参的值改变,而传值调用改变形参则对实参没有任何影响。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

[!--infotagslink--]

相关文章