在 C++(也包括 C)中通过引用传递变量的常用方法如下:
The usual way to pass a variable by reference in C++(also C) is as follows:
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;
}
但令我惊讶的是,我注意到当通过引用传递一个对象时,对象的名称本身就起到了作用(不需要 &
符号),并且在声明/函数定义 参数前不需要*
符号.下面的例子应该很清楚:
But to my surprise, I noticed when passing an object by reference the name of object itself serves the purpose(no &
symbol required) and that during declaration/definition of function no *
symbol is required before the argument.
The following example should make it clear:
// 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;
}
我无法理解为什么要对 class 进行这种特殊处理.即使是几乎像一个类的结构也不是这样使用的.对象名称是否和数组一样被视为地址?
I have problem understanding why is this special treatment done with class . Even structures which are almost like a class are not used this way. Is object name treated as address as in case of arrays?
让您感到困惑的是,声明为传递引用的函数(使用 &
) 不使用实际地址调用,即 &a
.
What seems to be confusing you is the fact that functions that are declared to be pass-by-reference (using the &
) aren't called using actual addresses, i.e. &a
.
简单的答案是将函数声明为传递引用:
The simple answer is that declaring a function as pass-by-reference:
void foo(int& x);
就是我们所需要的.然后它会自动通过引用传递.
is all we need. It's then passed by reference automatically.
你现在像这样调用这个函数:
You now call this function like so:
int y = 5;
foo(y);
和 y
将通过引用传递.
and y
will be passed by reference.
你也可以这样做(但为什么要这样做?咒语是:尽可能使用引用,需要时使用指针):
You could also do it like this (but why would you? The mantra is: Use references when possible, pointers when needed) :
#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;
}
输出:
yes, &a is b
这篇关于在 C++ 中通过引用传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!