this is a statement i have within a method(function )
what does "cout<<*this;" do?!
Collapse
X
-
Tags: None
-
this is the pointer to itself, so *this refers to itself. And cout<<*this prints it to the standard output.
Eg,
Code:class complex{ int x,y; .... ostream& operator<<(ostream&);//this defines the operator "<<" complex& operator/(complex); } complex complex::operator/(complex z){ if ((z==0)){//if divided by 0, print information cout<<*this<<" can't be divided by "<<z; return 0; } else{ ...; } }
-
You may not understand the this pointer.
C++ requires every function to receive all data using arguments.
If you look at your class member functions you will see that no member function has an argument for the class itself. Also yu will see that no member function has an argument for which object to work with.
What happens is that the address of the object is passed in by the compiler as an invisible first argument.
Code:class MyClass { private: int data; public: void Add(int x); }; void MyClass::Add(int x) { data = x; }
Code:void MyClass::Add(int x) { this->data = x; }
So if this is a MyClass*, then *this must be a MyClass variable.
Therefore, cout << *this is a call to an operator<< function that has an ostream and a MyClass argument.
Whereas cout << this is a call to an operator<< function that has an ostream and a MyClass* argument.
I hope this helps.Comment
Comment