-6

I'm looking through the c++ tutorial [http://www.cplusplus.com/doc/tutorial/classes2/ under "The keyword this"] and I'm confused on why a member function parameter has "&".

The code:

#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;   
}

Why does int isitme( CDummy& param) work and not int isitme( CDummy param )? Also how come in the function implementation it goes if( &param == this ), shouldn't &param only be used if the function declaration were int isitme( CDummy param )?

4

2 回答 2

2

It's a reference.

Normally, C++ is a pass-by-value language meaning that a copy is given to the functon.

By using &, you specify that the param variable is a reference, almost (a) like a pointer but without having to worry about indirection. The reference means you have access to the original variable for modification if necessary or (in this case) so that you can compare its address.

If you had passed by value, you would have gotten a copy which would have had a different address. What the isitme() method is doing is simply checking if a given CDummy variable is the one you're calling the method for, by checking the addresses of them as per the following code:

#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;
}

The output of that is:

1
0

(a) The main difference being that a reference has to refer to a real variable while a pointer may be NULL.

于 2013-06-19T02:31:12.707 回答
1

That is using the C++ lvalue reference language feature to pass a lvalue by-reference to the function, rather than having to use an explicit pointer like in C. Since references must be bound to objects, they cannot have a NULL value ... the reference-type variable basically aliases the object it references (i.e., there is no explicit dereferencing by the user like a pointer requires).

于 2013-06-19T02:30:29.200 回答