Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C++中使用联合定义类的简单但非平凡的例子是什么? C++中使用CUnion定义的类的简单但非平凡的例子? 该类应使用union定义 该类应该显式声明并实现构造函数和析构函数 该类应该有一些方法来证明此类类与使用类关键字定义的类之间的差异_C++_Oop - Fatal编程技术网

在C++中使用联合定义类的简单但非平凡的例子是什么? C++中使用CUnion定义的类的简单但非平凡的例子? 该类应使用union定义 该类应该显式声明并实现构造函数和析构函数 该类应该有一些方法来证明此类类与使用类关键字定义的类之间的差异

在C++中使用联合定义类的简单但非平凡的例子是什么? C++中使用CUnion定义的类的简单但非平凡的例子? 该类应使用union定义 该类应该显式声明并实现构造函数和析构函数 该类应该有一些方法来证明此类类与使用类关键字定义的类之间的差异,c++,oop,C++,Oop,也许是这样的: #include <new> enum EActive { ActiveNone, ActiveS, ActiveT }; struct S; struct T; union Foo { struct TagOnly { EActive current; TagOnly() : current(ActiveNone) { } } tag; S a; T b; void destroy() { if (tag.cu

也许是这样的:

#include <new>

enum EActive { ActiveNone, ActiveS, ActiveT };
struct S;
struct T;

union Foo
{
   struct TagOnly { EActive current; TagOnly() : current(ActiveNone) { } } tag;
   S a;
   T b;

   void destroy()
   {
     if      (tag.current == ActiveT) b.~T();
     else if (tag.current == ActiveS) a.~S();
   }

   void setS(S const & s)
   {
     destroy();
     S * const p = ::new (static_cast<void*>(&a)) S(s);
     tag.current = p ? ActiveS : ActiveNone;
   }

   // similar for setT(T const & t)

   ~Foo() { destroy(); }

   Foo() : tag() { }

};

这里我假设TagOnly、S和T共享共同的初始段。将S和T插入包装类struct UnionWrapper{EActive tag;U;/*…*/};可能更明智

这是作业还是面试问题?从问题的角度来看,显然是这样。你的问题到底是什么?你已经描述了你想要什么,但是什么阻止你写它?Stroustrup的C++编程语言说:一个带有构造函数、析构函数的类,或者复制操作不能是联合成员的类型,因为编译器不知道要销毁哪个成员。@TatianaRacheva:Stroustrup是最近十年的事了…@LaceySnr这既不是家庭作业,也不是采访问题。这是我在阅读一些关于类的C++文本时提出的问题。在我看来,虽然union和class关键字都可以用来定义类,但是union在某些用例中应该是非常有用的。但我受到了挑战,想不出这样的例子reading@MooingDuck:是的。。。。假设是:-有什么复杂的事情妨碍了一个简单的构造器吗?@MooingDuck:我这方面的懒惰是生活毁灭性的!它都被折叠到//。。。行。@TatianaRacheva:对不起,新的放置要求包含标题;我在最初的例子中忽略了这一点。现在添加它是为了完整性。