This post has already been read 1559 times!

Example :

// pointer_to_struct.cpp
#include 
using namespace std;

Define the structure in C++:

struct SPEED {
  int x;
};

Define the class in C++ :

class Computer // Standard way of defining the class
{
public:
  // Constructor 
  Computer();

  // Destructor
  ~Computer();

  // class method with Struct* parameter
  void setspeed ( SPEED *p );

  // class method
  int readspeed();

protected:

  int processorspeed;
};

Computer::Computer()
{
  //Constructors can accept arguments, but this one does not
  processorspeed = 0;
}

Computer::~Computer()
{
  //Destructors do not accept arguments
}

// method with Struct* parameter to set-up the speed 
void Computer::setspeed ( SPEED *p )
{
  processorspeed = p->x;
}
int Computer::readspeed()
{
  return processorspeed;
}

The main C++ program :

int main()
{
  // define a SPEED structure
  SPEED structure;

  // define a pointer to the SPEED structure
  SPEED *ptr;

  // initialise the x value of the SPEED structure with 12 
  structure.x = 12;

  // pass the adress of the SPEED structure for the SPEED pointer *ptr
  ptr = &structure; 

  // create the Computer object 
  Computer compute;

  // set-up the speed in Computer object with the (Struct*)
  compute.setspeed( ptr );

  // display the spreed value from the object 
  cout<< compute.readspeed();

  cin.get();
}

Comments are closed.

Post Navigation