Archived

This topic is now archived and is closed to further replies.

JasperW

Need help designing my variable type/struct...

Recommended Posts

I want to create a variable type like an int. But I want to overload the = so I can add some extra code. It is important that I can reference it exactly like a normal variable. So far I''ve come up with this:
  
typedef unsigned int u32

struct Int32 {
	u32 value;
	void operator=( const u32 valparam ) {
		this->value = valparam;
		// add some more code here later

	}
};
  
This allows me to do this:
  
Int32 myValue;
myValue = 254;
  
But it doesn''t work when I do this next:
  
fprint("%i", myValue);
  
How can I make it so that I can reference myValue like a normal int because I don''t want to do this: myValue.value. Maybe I''m looking in the wrong direction and I need to do something completely different. Or maybe it''s just impossible... Any help on this would be great. Thanks in advance, Jasper

Share this post


Link to post
Share on other sites
Not possible. But since you''re using C++ (I see you''re using overloaded operators), you can make it possible to use your struct as an intrinsic type with istream and ostream objects (another reason to ditch C library functions once and for all):

struct Int32
{
unsigned int value;
int &operator= (const unsigned int val)
{
value = val;
return *this;
}
friend istream &operator>> (istream &is, Int32 &i);
friend ostream &operator<< (ostream &os, Int32 &i);
};
//
istream &operator>> (istream &is, Int32 &i)
{
is >> i.value;
return is;
}
ostream &operator<< (ostream &os, Int32 &i)
{
os << i.value;
return os;
}
// you can now do this:
Int32 i = 45;
cout << i << endl;
cout << "Enter an integer number: ";
cin >> i;

Share this post


Link to post
Share on other sites
You could overload operator int for the class, then pass it in like this:
fprintf ("%d", (int) objectOfMyClass);

I believe the syntax is:
  
MyClass::operator int () const
{
return value;
}


Gotta jet, so feel free to flame if there are mistakes with this.

Share this post


Link to post
Share on other sites
That''s exactly what I was looking for! Thanks Stoffel.
Oluseyi: Although your method works it''s not a very useful alternative to me. I wanted to pass the value to any function that way not only output it. But thanks for your reply anyway.
Damn you guys are fast. Well thanks for solving this.

Jasper

Share this post


Link to post
Share on other sites