Make your own free website on Tripod.com
 
CHAPTER 5 : ARRAY, POINTER & REFERENCE
POINTER             #include <iostream.h>
            class samp{
                int i;
                public :
                    samp(int n) {i=n;}
                    void set_i(int n) {i=n;}
                    int get_i() {return i;}
            }

            void sqr_it(samp *o){
                o->set_i(o->get_i() * o->get_i());
                cout << "copy of a has i value of " << o->get_i();
                cout<<"\n";
            }

            main(){
                samp a(10);
                sqr_it(&a);
                cout <<" Now, a in main() has been changed : ";
                cout << a.get_i();
                return 0;
            }
 

Dynamic Memory allocation

                         char *word
                         word = new char[20];               char *word = new char[20];
              if (!word){
                cout << "Insufficient memory \n";
                exit(1);
              }             delete word;             #include <iostream.h>
            class samp {
                int i,j;
                public:
                    void set_ij( int a, int b){ i = a ; j = b;}
                    int get_product() { return i*j;}
            }
 

            main(){
                samp *p;
                p = new samp;
                if ( !p ){
                    cout << "Allocation error \n";
                    return 1;
                }
                p->set_ij(4,5);
                cout << "Product is : " << p->get_product() << "\n";
                return 0;
            }

            // Allocating dynamic objects
            #include <iostream.h>
            class samp {
                int i, j ;
                public :
                    samp (int a, int b) { i=a; j= b;}
                    int get_product() { return i*j;}
            }
 
            main(){
                samp *p;
                p = new samp(6,5);         // allocate object with initialization
                if (!p) {
                    cout << " Allocation error \n";
                    return 1;
                }

                cout << " Product is : " << p-> get_product() << "\n";
                delete p;
                return 0;
            }

            class myclass {
                int who;
                public :
                    myclass (int n){
                        who = n;
                        cout << " constructing " << who << "\n";
                    }
                    ~myclass(){
                        cout << "Destructing " << who << "\n";
                    }
                    int id() { return who;}
            }

            // o is passed by value
            void f( myclass *o){
                cout << "Received " << o->id() << "\n";
            }

            main(){
                myclass x(1);
                f(&x);
                return 0;
            }

            // Allocating dynamic objects
            #include <iostream.h>
            class samp {
                int i, j ;
                public :
                    void set_ij(int a, int b) { i=a; j=b;}
                    ~samp() { cout << " Destroying....\n";}
                    int get_product() { return i*j;}
            }
 
            main(){
                samp *p;
                int i;
                p = new samp[10];         // allocate object with initialization
                if (!p) {
                    cout << " Allocation error \n";
                    return 1;
                }

                for (i=0; i<10; i++)
                    p[i].set_ij(i,i);
                for (i=0; i<10; i++){
                    cout << "Product [" << i << "] is : ";
                    cout << p[i].get.product() << "\n";
                }
 
                delete []p;
                return 0;
            }

this Pointer

                #include <iostream.h>
                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;
                }

REFERENCE & ARRAY

                int int_value;
                int &ref = int_value;                 int_value++;            // alternative 1
                ref++;                     // altenative 2
           have same affect             //in standard C
            #include <iostream.h>
            void f(int *n);                    //use a pointer parameter
            main(){
                int i=0;
                f(&i);
                cout << "Here is i's new value : " << i << "\n";
                return 0;
            }

            void f (int *n) {
                *n = 100;                    //put 100 into the argument pointed to by n
            }
 

            //In C++
            #include <iostream.h>
            void f (int &n);                        //declare a reference parameter
            main(){
                int i=0;
                f(i);
                cout << "Here is i's new value : " << i << "\n";
                return 0;
            }

            // f() new uses a reference parameter
            void f (int &n) {
                //notice that no * is needed in the following statement
                n = 100;                    //put 100 into the argument used to call f()
            }

Passing Reference to objects

            #include <iostream.h>
            class myclass{
                int who;
                public:
                    myclass (int n) {
                        who = n;
                        cout << " constructing " << who << "\n";
                    }
 
                    ~myclass() { cout << " Destructing " << who << "\n"; }
                    int id() { return who;}
            }

            //o is passed by value
            void f(myclass o) {
                cout << "Received "<< o.id() << "\n";
            }

            main(){
                myclass x(1);
                f(x);
                return 0;
            }
 

            #include <iostream.h>
            myclass {
                int who;
                public:
                    myclass(int n) {
                        who = n;
                        cout << " Constructing " << who << "\n";
                    }
                    ~myclass(){
                        cout << " Destructing " << who << "\n";
                    }
                    int id() {
                        return who;
                    }
            };

            // now, o is passed by reference
            void f(myclass &o) {
                //note that - operator is still used !!!
                cout << " Received " << o.id() << "\n";
            }

            main() {
                myclass x(1);
                f(x);
                return 0;
            }

Returning Reference

            //A bounded array example
            #include <iostream.h>
            #include <stdlib.h>
            class array {
                int size; char *p;
                public:
                    array (int num);
                    char &put(int i);
                    char get (int i);
            };
 
            array::array (int num){
                p= new char [num];
                if (!p) {
                    cout << " Allocation error \n";
                    exit(1);
                }
                size = num;
            }

            // Put something into the array
            char &array :: put(int i){
                if (i < o || i >= size) {
                    cout << " Bound error !!!\n";
                    exit(1);
                }
                return p[i];                        // return reference to p[i]
            }

            // Get something from the array
            char array :: get (int i) {
                if (i < o || i >= size){
                    cout << " Bound error !!!\n";
                    exit(1);
                }
                return p[i];                        // return character
            }

            main() {
                array a(10);
                a.put(3) = 'X';
                a.put(2) = 'R';
                cout << a.get(3) << a.get (2);
                cout << "\n";
                // now generate run_time. boundary error
                a.put(11) = "!";
                return 0;
            }

Assignment 3

Ubahsuai class Time Fig. 6.10, pg. 396- 399 (C++ HOW T0 PROGRAM , 2nd Edition) dengan memasukkan ahli fungsi tick yang digunakan untuk menambahkan masa kepada saat dan disimpan dalam objek Time. Objek Time mesti sentiasa berada dalam keadaaan yang konsisten. Tulis satu main aturacara untuk  menguji ahli fungsi tick dengan membuat gelung yang bertujuan untuk mencetak masa sepanjang pengulangan gelung agar fungsi tick berjalan baik. Ujian anda mestilah berdasarkan perkara berikut :
a) Penambahan kepada minit berikutnya
b) Penambahan kepada jam berikutnya
c) Penambahan kepada hari berikutnya (contoh  11:59:59pm kepada 12:00:00 am)

Nota :

Tugasan ini hendaklah dihantar selewat-lewatnya pada 2/2/99. Tugasan anda tidak akan dilayan selepas tarikh tersebut.

//Declaration of the Time class
//Member functions defined in time3.cpp

//preprocessor directive that
//prevent multiple inclusions of header file

#ifndef TIME3_H
#define TIME3_H

class Time {
public:
 Time (int =0, int =0, int=0); //constructor

 //set functions
 void setTime(int, int, int); // set hour, minute, second
 void setHour(int); //set hour
 void setMinute(int); //set minute
 void setSecond(int); //set second

 //get functions
 int getHour();   //return hour
 int getMinute();  //return minute
 int getSecond();  //return second

 void printMilitary(); //output military time
 void printStandard(); //output standard time

private:
 int hour;   //0-23
 int minute;   //0-59
 int second;   //0-59
};
#endif
 

===================================================
 
//Member function definitions for Time class
#include "time3.h"
#include <iostream.h>

//constructor function to initialize private data
//calls member function setTime to set variables
//Default values are 0 (see class definition).

Time::Time(int ht, int min, int sec)
 { setTime(hr,min, sec);}

//Set the values of hour, minute, and second
void Time::setTime(int h, int m, int s)
{
 setHour(h);
 setMinute(m);
 setSecond(s);
}

//Set the hour value
void Time::setHour(int h)
 { hour = (h >= 0 && h < 24) ? h :0;}

//Set the minute value
void Time::setMinute(int m)
 {minute = (m >= 0 && m < 60) ? m : 0;}

//Set the second value
void Time::setSecond(int s)
 {second = (s >= 0 && s< 60) ? s:0;}

//Get the hour value
int Time::getHour() { return hour;}

//Get the minute value
int Time::getMinute() {return minute;}

//Get the second value
int Time::getSecond() {return second;}

//Print time is military format
void Time::printMilitary()
{
 cout<< (hour < 10 ? "0" : "" ) << hour << ":"
   << (minute < 10 ? "0" : "") << minute;
}

//Print time in standard format
void Time::printStandard()
{
 cout << (( hour ==0 || hour == 12)?12 : hour %12)
   << ":" << (minute < 10 ? "0" : "") << minute
   << ":" << (second < 10 ? "0" : "") << second
   << (hour < 12 ? " AM" : " pm" );
}

===================================================

//Demonstrating the Time class set and get functions
#include <iostream.h>
#include "time3.h"

void incrementatMinutes( Time &, const int );

int main()
{
 Time t;

 t.setHour(17);
 t.setMinute(34);
 t.setSecond(25);

 cout << "Result of setting all valid values:\n"
   << " Hour: " << t.getHour()
   << " Minute: " << t.getMinute()
   << " Second: " << t.getSecond();

 t.setHour(234);  //invalid hour set to 0
 t.setMinute(43);
 t.setSecond(6374); //invalid second set to 0

 cout << "\n\nResult of attempting to set invalid hour and "
   << " second:\n Hour: " << t.getHour()
   << " Minute: " << t.getMinute()
   << " Second: " << t.getSecond() << "\n\n";

 t.seTime(11,58,0);
 incrementMinute(t,3);

 return 0;
}

void incrementMinutes( Time &tt, const int count)
{
 cout << "incrementing minute " << count
   << " time:\nStart time: ";
 tt.printStandard();

 for (int i=0; i < count; i++) {
  tt.setMinute( (tt.getMinute() + 1) % 60);

  if (tt.getMinute() ==0)
   tt.setHour(( tt.getHour() + 1) % 24);

  cout << "\nminute + 1: ";
  tt.printStandard();
 }
 cout << endl;
}