Overloading input and output op. for pointers

Hey,

I need to overload the << and >> operator so that they can use pointers.
I am not sure if the question is clear enough.

Here is the code I am trying to make it work.
VS underlines drive.my_StorageCapacity and says expression must have class type.

So what should I do to make it work?
I tried FlashDrive* drive; since it was asking for class type,but no luck.

Is it possible of me to keep using << and >> for what they are doing right now and overload it again to use pointers?

Right now they are used for this.
1
2
3
cout<< "For drive 1 please enter total capacity(>0,and number only),\nand storage used(number only): ";
cin>> cap1 >> used1;
cout<<"\n"<<cap1 << " "<< used1<<"\n";




1
2
3
4
  std::istream& operator >> (std::istream& ins, FlashDrive*& drive) {
	ins >> drive.my_StorageCapacity >> drive.my_StorageUsed;
	
	return (ins);


1
2
3
std::ostream& operator << (std::ostream& outs, const FlashDrive* drive) {
	outs << *drive.my_StorageCapacity <<" "<< *drive.my_StorageUsed<<endl;
	return (outs);


I also want them to do this part.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
cs52::FlashDrive * drive3 = NULL;
// careful...
cout << drive3 << endl;

drive3 = &drive2;
cout << drive3 << endl;

drive3 = new FlashDrive();
cout <<"drive3";
cin  >> drive3;
cout << drive3 << endl;

delete( drive3 );


Thank you in advance.


You can't overload it for pointers.

But there's no need because you shouldn't be passing it pointers.

IE: instead of doing this:
1
2
cout << apointer;
cin >> apointer;


just do this:
1
2
cout << *apointer;
cin >> *apointer;


And instead of doing this:
 
apointer.whatever;


Do this:
 
apointer->whatever;
@Disch
Thank you for your help.
This is the assignment question.

Upgrade the class so that operator << and operator >> work well with pointers (that is, FlashDrive *). Youll need to re-overload these operators, adding the function:

friend std::ostream& operator <<( std::ostream& outs, const FlashDrive * drive );
friend std::istream& operator >>( std::istream& ins, FlashDrive * & drive );

HINT: Be very careful to test for NULL




apointer->whatever; solved my earlier problem but now program freezes when I start it.

How do I get this operator work well with pointers??
Whoops, you actually can overload for pointers because the ostream/istream object isn't a pointer.

My mistake!

That said.... EWWWWW @ This assignment. This is horrible and your teacher is teaching you something terrible. One would expect I/O'ing a pointer to I/O the pointer, and not I/O the data the pointer points to. Sloppy, sloppy, sloppy.


Anyway, the assignment shows you how to overload it. And you seem to be doing it correctly. If you fixed the -> problem, then it looks like you're doing everything except checking for null pointer (which the assignment tells you to do).

If the program is freezing, I couldn't tell you why without seeing updated code.
Topic archived. No new replies allowed.