Re: Operator Cast () Reference?
"Francesco S. Carta" <entul...@gmail.com> wrote:
Twixer Xev <twixer_...@hotmail.com> wrote:
I should clarify. Your assignments never invoke the cast operator. Put a
trace in there and you'll see what I mean. Assignment is covered by the
ctor's, which happen to be identicle for each class.
Ah, I see what you mean (silly me). In fact, if I declare the
constructors as explicit both assignments halt the compiler. Thanks
for the pointer :-)
In addition, if I got it straight:
-------
#include <iostream>
using namespace std;
class IntByRef {
public:
explicit IntByRef(int i) : datum(i) {};
operator int&() {
return datum;
}
private:
int datum;
};
class IntByVal {
public:
explicit 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; // prints 1
int& rint = intbyref;
rint = 42;
cout << intbyref << endl; // prints 42
// int& rint2 = intbyval; // chokes the compiler (*)
const int& crint = intbyval; // fine (**)
const int& crint2 = 78; // fine (**)
intbyval = IntByVal(10000);
cout << crint << endl; // prints 2
cout << crint2 << endl; // prints 78
cout << intbyval << endl; // prints 10000
return 0;
}
-------
(*) The compiler complains because it is not possible to create a non-
const reference to something that isn't modifiable.
(**) Fine? Seems so. Compiles and gives the expected result ;-)
--
FSC
http://userscripts.org/scripts/show/59948