#include <stdio.h>
struct B { int x,y; };
struct A : public B {
// This whines about "copy assignment operator not allowed in union"
//A& operator =(const A& a) { printf("A=A should do the exact same thing as A=B\n"); }
A& operator =(const B& b) { printf("A = B\n"); }
};
union U {
A a;
B b;
};
int main(int argc, const char* argv[]) {
U u1, u2;
u1.a = u2.b; // You can do this and it calls the operator =
u1.a = (B)u2.a; // This works too
u1.a = u2.a; // This calls the default assignment operator >:@
}
是否有任何解决方法可以u1.a = u2.a
使用完全相同的语法来完成最后一行,但让它调用operator =
(不关心它是 =(B&) 还是 =(A&)) 而不仅仅是复制数据?还是不受限制的联合(即使在 Visual Studio 2010 中也不支持)是唯一的选择?