为什么要使用&&引用;函数参数内部 我正在看C++教程[在“关键字”下],我很困惑为什么一个成员函数参数有“&”。p>

为什么要使用&&引用;函数参数内部 我正在看C++教程[在“关键字”下],我很困惑为什么一个成员函数参数有“&”。p>,c++,C++,守则: #include "stdafx.h" #include <iostream> class CDummy { public: int isitme( CDummy& param ); // <-- Having trouble understanding this }; int CDummy::isitme( CDummy& param ) // <-- Having trouble understanding this {

守则:

#include "stdafx.h"
#include <iostream>

class CDummy {
public:
    int isitme( CDummy& param );    // <-- Having trouble understanding this
};

int CDummy::isitme( CDummy& param )    // <-- Having trouble understanding this
{
    if( &param == this) 
        return true;
    else
        return false;
}

int main ()
{
    CDummy a;
    CDummy *b = &a;
    if ( b->isitme(a) )
        std::cout<< "yes, &a is b";

    return 0;   
}
#包括“stdafx.h”
#包括
类CDummy{
公众:

int isitme(CDummy和param)//这是使用C++ LValk引用语言特性来传递一个LValk到函数,而不是使用像C.那样的一个显式指针,因为引用必须绑定到对象,它们不能有<代码> null <代码>值…引用类型变量基本上别名引用它的对象。(也就是说,用户不需要像指针那样明确地取消引用)。

它是一个引用

通常,C++是一个传递值语言,意味着拷贝被赋给函数。 通过使用

&
,您可以指定
param
变量是一个引用,几乎(a)像一个指针,但不必担心间接性。该引用意味着您可以访问原始变量进行修改(如果需要),或者(在本例中)可以比较其地址

如果您按值传递,您将得到一个具有不同地址的副本。
isitme()
方法所做的只是检查给定的
CDummy
变量是否是您调用该方法的变量,方法是根据以下代码检查它们的地址:

#include <iostream>

class CDummy {
public:
    int isitme (CDummy &x) {
        return &x == this;
    }
};

int main (void) {
    CDummy a, b;
    std::cout << a.isitme (a) << '\n';   // 1 = true
    std::cout << a.isitme (b) << '\n';   // 0 = false
    return 0;
}


(a) 主要区别在于引用必须引用实变量,而指针可能为空。

在手头的任何教育材料中查找引用。但是当您将a传递到b->isitme()时。它不是引用,对吗?Splaty,是的,它是引用。请参阅我更新的答案。我以前从未见过函数参数中使用的(&D)。我一直认为指针是广泛使用的。通过说“无需担心间接寻址”你是说不担心星号吗?“SpLIPY,指针是C中引用的方式,但是它有问题,比如需要间接地去理解底层变量。我认为引用是C++的最好特征之一,当然是一个应该考虑的ISOC23:)
1
0