Re: Assign the value of a class to an unsigned integer (built-in)
type
On 6/1/2010 1:04 PM, Jonathan Lee wrote:
On Jun 1, 12:42 pm, Peter Olcott<NoS...@OCR4Screen.com> wrote:
I would like to be able to assign the value of this class to an unsigned
integer using operator=() syntax.
You can overload casting operators:
class Dummy {
unsigned long x;
public:
Dummy(unsigned long y): x(y) { }
operator unsigned long() const { return x; }
};
#include<iostream>
using namespace std;
int main() {
Dummy d(5);
unsigned long t = d;
std::cout<< t<< std::endl;
}
I don't personally recommend it, though. It invites
conversions where you don't intend it, for one thing.
To the OP:
A better way, perhaps, would be to write a 'toXXX()' const member
function and use it *explicitly*. With a conversion function like 'op
long', a typo with an object of your type used in an arithmetic
expression can easily go unnoticed (and that's what Jonathan's warning
you about).
Compare:
unsigned long a42(42);
Dummy aa42(84);
...
unsigned long ul_result = aa42; // If no conversion exists, error.
// Actually, it was a typo with
// the intended initializer 'a42'.
Otherwise
unsigned long ul_result = s42.toULong(); // no doubt
V
--
I do not respond to top-posted replies, please don't ask