問(wèn)題描述
在 C++(也包括 C)中通過(guò)引用傳遞變量的常用方法如下:
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;
}
但令我驚訝的是,我注意到當(dāng)通過(guò)引用傳遞一個(gè)對(duì)象時(shí),對(duì)象的名稱(chēng)本身就起到了作用(不需要 &
符號(hào)),并且在聲明/函數(shù)定義 參數(shù)前不需要*
符號(hào).下面的例子應(yīng)該很清楚:
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;
}
我無(wú)法理解為什么要對(duì) class 進(jìn)行這種特殊處理.即使是幾乎像一個(gè)類(lèi)的結(jié)構(gòu)也不是這樣使用的.對(duì)象名稱(chēng)是否和數(shù)組一樣被視為地址?
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?
推薦答案
讓您感到困惑的是,聲明為傳遞引用的函數(shù)(使用 &
) 不使用實(shí)際地址調(diào)用,即 &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
.
簡(jiǎn)單的答案是將函數(shù)聲明為傳遞引用:
The simple answer is that declaring a function as pass-by-reference:
void foo(int& x);
就是我們所需要的.然后它會(huì)自動(dòng)通過(guò)引用傳遞.
is all we need. It's then passed by reference automatically.
你現(xiàn)在像這樣調(diào)用這個(gè)函數(shù):
You now call this function like so:
int y = 5;
foo(y);
和 y
將通過(guò)引用傳遞.
and y
will be passed by reference.
你也可以這樣做(但為什么要這樣做?咒語(yǔ)是:盡可能使用引用,需要時(shí)使用指針):
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
這篇關(guān)于在 C++ 中通過(guò)引用傳遞對(duì)象的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!