Printing data in structs[Sorta]

I'm trying to print out 'shell' type structs by overloading the stream insertion operator.

So far, all of my efforts yield only memory addresses.

How do I get the value out of these addresses? I just can't seem to figure it out.

Note: I'm using an anonymous union

Also, this isn't exactly mission critical - I'm just playing with features of the language for fun in my spare time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
struct shell
{
	union
	{
		long l;
		struct
		{
			short s1;
			short s2;
		} s;
		char n[4];
	};
}sh;

bool operator<<(ostream &out, shell &s);

int main()
{
	
	string line;
	
	getline(cin, line);
	stringstream(line) >> sh.l;
	
	cout << "sh.l: " << sh.l << endl; // This works fine
	
	cout << &sh << endl; // This doesn't
	return 0;
}

bool operator<<(ostream &out, shell &s)
{
	out << s.l;
}
Last edited on
line 15 & 31: why does a function returning bool not returning anything? and doesn't it supposed to return a reference to the ostream object

line 27: you're asking cout to print the address of sh
I know what that is printing silly! =p I mentioned it in my OP.


I'm just overloading the default behavior of the stream insertion operator to handle a shell type struct. I didn't bother to return anything because I'm just playing with code, and the return isn't required (I think) to get the printing behavior. Seeing as how it /does/ print out.


The thing is, I can't de-reference s.l using *s.l to get the value. I get a compile error.

How would I make it print out s.l's value instead of address, considering that dereferencing it isn't working?

I would greatly appreciate any insight on the matter.
Last edited on
sorry I still can't follow your train of thought here,

Sethe wrote:
I'm just overloading the default behavior of the stream insertion operator to handle a shell type struct. I didn't bother to return anything because I'm just playing with code, and the return isn't required (I think) to get the printing behavior. Seeing as how it /does/ print out.
to me this mean writing something like:
1
2
3
4
5
std::ostream& operator<<(std::ostream& ostr, UserType &obj)
{
      ostr << /* object members */ ;
      return ostr;
}


if you want to dereference an object and print it, it's just like normal
1
2
3
4
5
6
7
8
9
int* pvar = &var; // var has already been declared & initialized
// do something with *pvar
...
cout << *pvar; // to see the results, this is the 'normal' overloading of <<

// using a user-defined object is no different
UserType obj; // obj is initialized with empty contructor
UserType* pobj = &obj;
cout << *pobj; // now you're calling the overloaded << defined above and dereferencing your object 


what I meant with the line 27 remark was you're not using the overloaded << operator that you defined ;)
Topic archived. No new replies allowed.