What is purpose of this
keyword. Doesn't the methods in a class have access to other peer members in the same class ? What is the need to call a this
to call peer methods inside a class?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Do the Java Integer and Double objects have unnece
- Why does const allow implicit conversion of refere
- thread_local variables initialization
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
The
this
pointer is a way to access the current instance of particular object. It can be used for several purposes:It also allows you to test for self assignment in assignment operator overloads:
One more purpose is to chaining object: Consider the following class:
If you wanted to add 5, subtract 3, and multiply by 4, you’d have to do this: #include int main() { Calc calc; calc.add(5); // returns void calc.sub(3); // returns void calc.mult(4); // returns void
However, if we make each function return *this, we can chain the calls together. Here is the new version of Calc with “chainable” functions:
Note that add(), sub() and mult() are now returning *this. Consequently, this allows us to do the following:
We have effectively condensed three lines into one expression.
Copied from :http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/
It allows you to get around members being shadowed by method arguments or local variables.
For example if you write an
operator=()
you must check for self assignment.The double colon in c++ is technically known as "Unary Scope resolution operator". Basically it is used when we have the same variable repeated for example inside our "main" function (where our variable will be called local variable) and outside main (where the variable is called a global variable). C++ will alwaysexecute the inner variable ( that is the local one). So imagine you want to use the global variable "Conundrum" instead the local one just because the global one is expressed as a float instead of as an integer:
So in this case the program will use our float Conundrum instead of the int Conundrum.