C++/Pointer/Pointer Object

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

A base pointer to access derived objects

#include <iostream>
using namespace std;
class BaseClass {
  int i;
public:
  void setInt(int num) { 
    i = num; 
  }
  int getInt() { 
    return i; 
  }
};
class derived: public BaseClass {
  int j;
public:
  void setJ(int num) { 
     j = num; 
  }
  int getJ() { 
     return j; 
  }
};
int main()
{
  BaseClass *baseClassPointer;
  derived d;
  baseClassPointer = &d;     // BaseClass pointer points to derived object
                             // access derived object using BaseClass pointer
  baseClassPointer->setInt(10);
  cout << baseClassPointer->getInt() << " ";
  return 0;
}


Incrementing and decrementing an object pointer.

#include <iostream> 
using namespace std; 
 
class myClass { 
  int num; 
public: 
  void set_num(int val) { 
     num = val; 
  } 
  void show_num(){ 
     cout << num << endl; 
  } 
}; 
  
int main() 
{ 
  myClass ob[2], *objectPointer; 
 
  ob[0].set_num(10);              // access objects directly 
  ob[1].set_num(20); 
 
  objectPointer = &ob[0];         // obtain pointer to first element 
  objectPointer->show_num();      // show value of ob[0] using pointer 
 
  objectPointer++;                // advance to next object 
  objectPointer->show_num();      // show value of ob[1] using pointer 
 
  objectPointer--;                // retreat to previous object 
  objectPointer->show_num();      // again show value of ob[0] 
 
  return 0; 
}


Pointers to Objects

#include <iostream>
using namespace std;
class myclass {
  int i;
public:
  myclass(int j) { 
     i = j; 
  }
  int getInt() { 
     return i; 
  }
};
int main()
{
  myclass ob(88), *objectPointer;
  objectPointer = &ob;             // get address of ob
  cout << objectPointer->getInt();  // use -> to call getInt()
  return 0;
}


When a pointer is incremented, it points to the next element of its type

#include <iostream>
using namespace std;
class MyClass {
  int i;
public:
  MyClass() { 
    i=0; 
  }
  MyClass(int j) { 
    i=j; 
  }
  int getInt() { 
    return i; 
  }
};
int main()
{
  MyClass myObject[5] = {1, 2, 3,4,5};
  MyClass *objectPointer;
  int i;
  objectPointer = myObject; 
  for(i=0; i<5; i++) {
    cout << objectPointer->getInt() << "\n";
    objectPointer++; 
  }
  return 0;
}