在C ++中通过引用传递对象 [英] passing object by reference in C++
问题描述
在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;
}
我有问题了解为什么这个特殊的处理类。即使是几乎像类的结构也不会这样使用。 对象名称是否像数组一样被视为地址?
推荐答案
是声明为通过引用传递的函数(使用&
)不使用实际地址调用,即& ; 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);
是我们需要的。
您现在可以这样调用此函数:
You now call this function like so:
int y = 5;
foo(y);
和 y
将通过引用传递。
您也可以这样做(但是为什么?)咒语是:尽可能使用引用,需要时指针 / p>
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 ++中通过引用传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!