home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_07_06 / v7n6035a.txt < prev    next >
Text File  |  1989-07-25  |  1KB  |  71 lines

  1. // VEC.CXX: An integer vector to illustrate the
  2. // need for the copy-initializer
  3. #include <stdio.h>
  4.  
  5. class vec {  // an integer vector
  6.   int size;
  7.   int * vp;
  8. public:
  9.   vec(int i = 0, int j = 0);
  10.   vec(vec & rv);
  11.   ~vec() { delete vp; }
  12.   vec operator=(vec & rv);
  13.   void print(char * msg = "");
  14.   int & operator[](int x);
  15.   int length() { return size; }
  16. };
  17.  
  18. vec::vec(int i, int j) {
  19.   vp = new int[size = i];
  20.   for (int x = 0; x < size; x++)
  21.     vp[x] = j;
  22. }
  23.  
  24. vec::vec(vec & rv) {
  25.   vp = new int[size = rv.size];
  26.   for (int x = 0; x < size; x++)
  27.     vp[x] = rv.vp[x];
  28. }
  29.  
  30. vec vec::operator=(vec & rv) {
  31.   delete vp; // release old memory
  32.   vp = new int[size = rv.size];
  33.   for (int x = 0; x < size; x++)
  34.     vp[x] = rv.vp[x];
  35.   return *this;  // return a copy of this object
  36. }
  37.  
  38. void vec::print(char * msg) {
  39.   printf("%s",msg);
  40.   for(int x = 0; x < size; x++)
  41.     printf("%d ",vp[x]);
  42.   printf("\n");
  43. }
  44.  
  45. int & vec::operator[](int x) {
  46.   if (x < size)
  47.     return vp[x];
  48.   else {
  49.     puts("vec index out of range");
  50.     exit(1);
  51.   }
  52. }
  53.  
  54.  
  55. // pass in by value, return by value:
  56. vec func1(vec value) {
  57.   if (value.length() >= 1)
  58.     value[0] = 0;
  59.   return value;
  60. }
  61.  
  62. main() {
  63.   vec A(4,3);
  64.   vec B;
  65.   A.print("A: ");
  66.   B.print("B: ");
  67.   B = func1(A);
  68.   A.print("A after func1: ");
  69.   B.print("B after func1: ");
  70. }
  71.