2012-02-02 7 views
9

staram się znaleźć adres this wskaźnika, ale kod ten pokazuje dziwne błąd:adres tej

#include <iostream> 
using namespace std; 
class Base 
{ 
    public: 
     void test() 
     { 
      void *address_of_this =&this; 
      cout<<address_of_this<<endl; 
     } 
}; 

int main() 
{ Base k; 
    k.test(); 

    return 0; 
} //error non-lvalue in unary'&' 

można wyjaśnić ten błąd?
Wskazuje również, co jest nielegalne w przyjmowaniu adresu this?

+0

Spróbuj dodać spację po znaku = = – Alexander

Odpowiedz

20

this to wskaźnik zawierający adres do "bieżącego obiektu". Nie jest to zmienna, która jest gdzieś przechowywana (lub może nawet zostać zmieniona), jest specjalnym słowem kluczowym o tych właściwościach.

Jako takie, jego adres nie ma sensu. Jeśli chcesz wiedzieć, adres "bieżącego obiektu" można po prostu wyjście:

std::cout << this; 

lub przechowywać jako

void* a = this; 
+2

Wreszcie ... głos rozsądku. – Mankarse

+6

W standardese: 'this' jest rwartością (a nie typem klasy), więc nie ma adresu. –

+0

W standardzie ponownie "this" to _prwalue_ - _pure-rvalue_. – Xupicor

7

Cytowanie 2003 C++ standard:

5.1 [expr.prim] The keyword this names a pointer to the object for which a nonstatic member function (9.3.2) is invoked. ... The type of the expression is a pointer to the function’s class (9.3.2), ... The expression is an rvalue.

5.3.1 [expr.unary.op] The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified_id.

Mówiąc po prostu, & wymaga lwartości. this to wartość r, a nie l, tak jak wskazuje komunikat o błędzie.