形参的参数是地址,但调用时实参是对象.doc

来源:百度知道 编辑:UC知道 时间:2024/06/05 04:57:03
#include <iostream>
using namespace std;
class test
{
int i;
public:
test(){cout<<"构造函数"<<endl;}
~test(){cout<<"析构造函数"<<endl;}
void setvalue(int m){i=m;}
int getvalue(){return(i);}
};
void show(test &newtest)
{
cout<<newtest.getvalue()<<endl;
}
test change(test newtest,int m)
{
newtest.setvalue(m);
show(newtest);
return(newtest);
}
void main()
{
test mytest;
mytest.setvalue(10);
show(mytest);
change(mytest,100);
show(mytest);
}

上面的程序在调用show函数时,实参是对象而show的形参是对象的地址,这不是明显的实参与形参的类型不符吗?但为什么这个程序又能正常运行呢?

&为取地址运算符,这里为引用形参
在调用函数时,给形参分配内存单元,并将实参对应的值
传递给形参(在函数未被调用之前,形参并不占内存单元)
&newtest
|地址|————>|mytest|

这里是引用形参。