C++/Class/this — различия между версиями

Материал из C\C++ эксперт
Перейти к: навигация, поиск
м (1 версия: Импорт контента...)
 
м (1 версия: Импорт контента...)
 
(нет различий)

Текущая версия на 10:25, 25 мая 2010

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;
}