variable assignment - C++ unrestricted union workaround -
#include <stdio.h> struct b { int x,y; }; struct : public b { // whines "copy assignment operator not allowed in union" //a& operator =(const a& a) { printf("a=a should exact same thing a=b\n"); } a& operator =(const b& b) { printf("a = b\n"); } }; union u { a; b b; }; int main(int argc, const char* argv[]) { u u1, u2; u1.a = u2.b; // can , calls operator = u1.a = (b)u2.a; // works u1.a = u2.a; // calls default assignment operator >:@ }
is there workaround able last line u1.a = u2.a
exact same syntax, have call operator =
(don't care if it's =(b&) or =(a&)) instead of copying data? or unrestricted unions (not supported in visual studio 2010) option?
this means structure a
can have default copy assignment operator (generated compiler) or not have @ (declared private no definition).
you confusing copy assignment operator vs assignment operator here. copy assignment operator special case. in example, a& operator =(const b & b)
not classified copy assignment operator, assignment operator , c++ not restrict having in class being put union. when object being assigned copying, copy assignment operator (that have called default assignment operator) still called.
there no workaround let have custom copy assignment operator. first solution comes mind have operator free function, not allowed either.
so have come alternative function instead of assignment. closest thing use other operator, example <<
:
#include <stdio.h> struct b { int x, y; }; struct : b { a& operator =(const b& b) { printf("a = b\n"); return *this; } }; union u { a; b b; }; & operator << (a & lhs, const b & rhs) { printf ("a & operator << (const & lhs, const b & rhs)\n"); return lhs = rhs; } int main () { u u1, u2; u1.a << u2.b; u1.a << u2.a; }
this output following:
$ ./test & operator << (const & lhs, const b & rhs) = b & operator << (const & lhs, const b & rhs) = b
just in case, there unrestricted unions in c++0x.
hope helps.
Comments
Post a Comment