C++ 无限制 union 解决方法

标签 c++ variable-assignment copy-constructor unions default-constructor

#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&)) 而不仅仅是复制数据?还是不受限制的 union (甚至在 Visual Studio 2010 中也不支持)是唯一的选择?

最佳答案

C++ does not allow for a data member to be any type that has a full fledged constructor/destructor and/or copy constructor, or a non-trivial copy assignment operator.

这意味着结构A只能有一个默认的复制赋值运算符(由编译器生成)或根本没有(声明为私有(private)且没有定义)。

你在混淆copy assignment operator vs assignment operator这里。复制赋值运算符是一个特例。在您的示例中,A& operator =(const B & b)没有被归类为复制赋值运算符,它只是一个赋值运算符,C++ 不限制您将它放在要放入 union 的类中。但是,当对象通过复制进行赋值时,复制赋值运算符(您称为默认赋值运算符)仍将被调用。

没有让您拥有自定义复制赋值运算符的解决方法。想到的第一个解决方案是让这个运算符成为一个自由函数,但这也是不允许的。

所以你必须想出一些替代函数而不是赋值。最接近的是使用其他运算符,例如 << :

#include <stdio.h>

struct B { int x, y; };

struct A : B
{
    A& operator =(const B& b) { printf("A = B\n"); return *this; }
};

union U {
    A a;
    B b;
};

A & operator << (A & lhs, const B & rhs)
{
    printf ("A & operator << (const A & lhs, const B & rhs)\n");
    return lhs = rhs;
}

int
main ()
{
    U u1, u2;
    u1.a << u2.b;
    u1.a << u2.a;
}

这将输出以下内容:

$ ./test 
A & operator << (const A & lhs, const B & rhs)
A = B
A & operator << (const A & lhs, const B & rhs)
A = B

以防万一,有unrestricted unions in C++0x .

希望对您有所帮助。

关于C++ 无限制 union 解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3884770/

相关文章:

C++11:显式复制值以用作右值引用的最短方法

c++ - 为具有 shared_ptr 数据成员的类复制构造函数?

c++ - Cocos2dx中通过plist文件加载动画

c++ - vim c++ 断行

c++ - unordered_map 的正确值

c++ - 类构造函数内部的成员函数调用

c++ - 导致过载解析头痛的原因是什么?

R:向量元素的全局分配仅在函数内部有效

c - 将一个int数组(只有一个元素)分配给c中的一个整数

java - 如何修复 'not a statement'?