Click here to Skip to main content
15,922,696 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I was looking over some online tutorials/examples on operator overloading. They where very informative but I was looking for something a little different.

The tutorials had:
#include<iostream.h>
#include<fstream.h>

class ThreeD
{
  int x,y,z;
public:
  ThreeD(int i,int j,int k){
    x=i;
    y=j;
    z=k;
  }
  
  friend istream& operator>>(istream& stream,ThreeD ob);
};


istream& operator>>(istream& stream,ThreeD  ob)
{
  stream>>ob.x>>ob.y>>ob.z;
  return stream;
}
main()
{
  
  ifstream in("test");
  
  ThreeD o3(0,0,0),o4(0,0,0);
  in>>o3>>o4;
  return 0;
}


but I was wondering if you could do something more like:
ThreeD o3;

o3 >> 0 >> 20 >> 6;



I know STL has a class for this. I want to know if it can be done this way
Posted

1 solution

ThreeD o3;

o3 >> 0 >> 20 >> 6;


Would mean you defined an operator something like:

ThreeD& operator>> (ThreeD &obj, int x)
{
    // What do you want to do here???

    return obj
}


Do you actually mean:

ThreeD o3;

o3 << 0 << 20 << 6;


In which case you'd define something like:

class ThreeD
{
  int x,y,z;

  int last;
public:
  ThreeD() { 
    x = y = z = 0;
    last = 0;
  }

  ThreeD(int i,int j,int k){
    x=i;
    y=j;
    z=k;
    last = 3;
  }
  
  friend ThreeD& operator>>(ThreeD& obj,int i);
};
 
ThreeD& operator>>(ThreeD& obj, int i)
{
    switch (obj->last) {
       case 0:   obj->x = i;  break;
       case 1:   obj->y = i;  break;
       case 2:   obj->z = i;  break;
       default:
          throw "Already got three numbers can't input any more!";
    }
    obj->last++;
 
    return obj;
}
 
Share this answer
 
Comments
me3344 12-Jul-11 21:00pm    
Had to change the (->)'s to (.)'s but it works! thanx =)
TRK3 13-Jul-11 12:57pm    
Oops! Good thing the compiler was paying more attention than I was. Glad to hear it worked for you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900