Re: Operator Cast () Reference?
Immortal Nephi <Immortal_Ne...@hotmail.com> wrote:
Someone posted his Byte class code on the previous thread=
.. I have a
question about operator cast (). Please explain the difference
between local object and reference object. Why do you need reference
object?
The object is still the same if you remove ampersand betw=
een operator
unsigned char and ().
class Byte {
public:
Byte( unsigned char& c ) : c_( c ) {
}
Byte& operator=( unsigned char val ) {
c_ = val;
return *this;
}
operator unsigned char&() { // ???? reference ????
return c_;
}
// operator unsigned char() { // ???? local ????
// return c_;
// }
private:
unsigned char& c_;
};
int main() {
unsigned char data = 0x41, data2 = 0x23;
Byte byte( data );
data2 = byte; // data2 is overwritten from 0x23 to 0x41
return 0;
}
Eh, nice question... somebody here would eventually be able to explain
why my code gives such an output:
-------
#include <iostream>
using namespace std;
class IntByRef {
public:
IntByRef(int i) : datum(i) {};
operator int&() {
return datum;
}
private:
int datum;
};
class IntByVal {
public:
IntByVal(int i) : datum(i) {};
operator int() {
return datum;
}
private:
int datum;
};
int main()
{
int one = 1;
int two = 2;
IntByRef intbyref(one);
IntByVal intbyval(two);
cout << intbyref << endl;
cout << intbyval << endl;
intbyref = 42;
intbyval = 42;
cout << intbyref << endl;
cout << intbyval << endl;
return 0;
}
-------
Output:
-------
1
2
42
42
-------
I would have expected the compiler to choke on the assignment to
intbyval, or, at least, to print "2" as last line of output...
(just for the sake of learning something new...)