How to use "this" in a member function?

I wrote a member function of the Node class to read the node tree in postfix order.

It will be called by the Node instance, which is the root of the Node tree.

So: N.postfix ();

they seem illeagal:

*this->left.postfix(); *this->right.postfix(); 

What is the right way to do this?

 class Node { public: const char *cargo; int depth; Node *left; Node *right void Node::postfix() { if (this==__nullptr) { return; } else { *this->left.postfix(); *this->right.postfix(); out<<*this->cargo<<"\n"; return; } }; 
+1
source share
3 answers

In a member function, you usually do not need to use this to access class members; you can just use:

 left->postfix(); 

and etc.

If you have function parameters or other local variables with the same name as the class variable, you can use this to refer to a member variable, for example,

 this->left->postfix(); 

The reason your code is illegal is because it does not properly treat left as a pointer. You need to dereference left with -> to access your members, as shown in the correct code here. (You can also use the equivalent of (*left).postfix() , but that just makes you use more parentheses without real benefit.)

Using the indirectness operator * at the beginning of an expression is also incorrect, because it is applied to the result of postfix() (i.e. it does disassembly, which returns postfix() ). postfix() returns nothing, so this is an error. It is important to remember that the operators . and -> have a higher priority than * .

+10
source

The operator -> searches for a pointer, so additional * will cause problems. You can do it:

 this->left->postfix(); 

Or that:

 (*this).left->postfix(); 
+6
source
 *this->left.postfix(); 

"Separate the return value of calling postfix () in the variable 'left' of that variable."

 this->left->postfix(); //or (*this->left).postfix(); 

"Call postfix () on the separation variable" left "of this section."

+1
source

Source: https://habr.com/ru/post/1308884/


All Articles