通常的方法是通过引用传递变量在C++(也是C)中如下:
void _someFunction(dataType *name){ // dataType e.g int,char,float etc.
/****
definition
*/
}
int main(){
dataType v;
_somefunction(&v); //address of variable v being passed
return 0;
}
但令我惊讶的是,我注意到当通过引用传递对象对象本身的名称服务于目的(没有&
需要符号)并且在函数的声明/定义期间没有*
参数之前需要符号。
下面的例子应该可以清楚地说明:
// this
#include <iostream>
using namespace std;
class CDummy {
public:
int isitme (CDummy& param); //why not (CDummy* param);
};
int CDummy::isitme (CDummy& param)
{
if (¶m == this) return true;
else return false;
}
int main () {
CDummy a;
CDummy* b = &a;
if ( b->isitme(a) ) //why not isitme(&a)
cout << "yes, &a is b";
return 0;
}
我无法理解为什么要在课堂上进行这种特殊处理。即使是几乎像类的结构也不会以这种方式使用。对象名称是否像数组一样被视为地址?
似乎让您感到困惑的是,声明为按引用传递的函数(使用&
)不使用实际地址调用,即&a
.
简单的答案是将函数声明为按引用传递:
void foo(int& x);
这就是我们所需要的。然后它会自动通过引用传递。
现在您可以像这样调用该函数:
int y = 5;
foo(y);
and y
将通过引用传递。
你也可以这样做(但为什么要这么做?口头禅是:尽可能使用引用,需要时使用指针) :
#include <iostream>
using namespace std;
class CDummy {
public:
int isitme (CDummy* param);
};
int CDummy::isitme (CDummy* param)
{
if (param == this) return true;
else return false;
}
int main () {
CDummy a;
CDummy* b = &a; // assigning address of a to b
if ( b->isitme(&a) ) // Called with &a (address of a) instead of a
cout << "yes, &a is b";
return 0;
}
Output:
yes, &a is b
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)