C++/Class/this

Материал из C\C++ эксперт
Перейти к: навигация, поиск

how the this class pointer works

  
#include <iostream>  
using namespace std;
class MyClass {  
  int i;  
public:  
  void load_i(int val) { this->i = val; }
  int get_i(void) { return this->i; } 
};  
main(void){  
  MyClass o;  
  o.load_i(100);
  cout << o.get_i();
  return 0;  
}


this points yourself

   
#include <iostream>
#include <string.h>
using namespace std;
class SomeClass 
{
 public:
   void show_with_this(void) 
   {
     cout << "Book: " << this->title << endl;
     cout << "Author: " << this->author << endl; 
   };
   void show_without_this(void) 
   {
     cout << "Book: " << title << endl;
     cout << "Author: " << author << endl; 
   };
   
   SomeClass(char *title, char *author) 
   {
     strcpy(SomeClass::title, title);
     strcpy(SomeClass::author, author);
   };
 private:
   char title[256];
   char author[256];
};
int main(void)
{
   SomeClass book("A", "B");
   book.show_with_this();
   book.show_without_this();
}


Using the this pointer to refer to object members.

  
#include <iostream>
using std::cout;
using std::endl;
class Test {
public:
   Test( int = 0 );
   void print() const;
private:
   int x;
}; 
Test::Test( int a ) { x = a; }
void Test::print() const   
{
   cout << "        x = " << x
        << "\n  this->x = " << this->x
        << "\n(*this).x = " << ( *this ).x << endl;
}
int main()
{
   Test testObject( 12 );
   testObject.print();
   return 0;
}