I'm experienced in Python and now learning cpp to speed up code. After reading a bit this
seems to be the cpp equivalent of self
. I found a question explaining the difference from a cpp user's point of view but I'd like to know any differences for a python user's point of view.
The major difference is that you mostly don't need this
in C++, because there is a syntactic distinction between defining a member and referring to it.
Contrast
Python:
class Foo:
def __init__(self):
self._bar = 42
def baz(self):
return self._bar += 1
C++:
class Foo {
int bar = 42;
public:
int baz() { return bar += 1; }
}
In addition to the answer already given, self
in Python is just a conventional name chosen for the first argument of a class method which refers to the object itself that the method is called on directly.
In C++, this
is a keyword that is not explicitly specified as a parameter of a non-static class member function, but automatically refers to the instance that such a function is called on as pointer .
That means this
is not a reference to the object, but a pointer to it. So
this.member = 4;
is not possible. this
must be dereferenced first to obtain a reference to the object from the pointer:
this->member = 4;
or (uncommonly)
(*this).member = 4;
With a few exceptions relating to name lookup in templates, the names of members refer to the current instances member automatically, as explained in the other answer, so this->
can be dropped, usually:
member = 4;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.