I have a class whose only data member is a 32 bit unsigned integer. That is, the class looks like this:
class A {
protected:
unsigned int bits;
/* ... some methods ... */
public:
/* ... some methods ... */
};
But I want it to also be able to implicitly convert to and from 32 bit unsigned integers. So I added in a copy constructor as well as a casting operator:
class A {
protected:
unsigned int bits;
/* ... some methods ... */
public:
A(): bits(0) {} // default constructor
A(const unsigned int i): bits(i) {} // convert from unsigned int to A
operator unsigned int() { return bits; } // convert from A to unsigned int
/* ... some methods ... */
};
So now for example, I can do the following things:
int main () {
// default constructor
A a0 = A();
// convert from unsigned int
A a1 = 1 + 2;
// conversions between the two types:
unsigned int result = (a0 & a1 + 5) / 2;
}
However I'm struggling to get it to work with const
types. In particular, the following doesn't work:
int main () {
const A a = 5; // works
unsigned int i = a; // compiletime error
}
It says "No suitable conversion function from 'const A' to 'unsigned int' exists.". I'm using Visual Studio 2010 with the default compiler as provided by microsoft.
What conversion function do I need to create for it to work properly?