作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在这里阅读了 C++ 中的可区分 union :http://www.stroustrup.com/C++11FAQ.html#unions
如果我想创建一个递归类型的 union 怎么办?
例如,考虑以下内容:
class Obj {
enum class Type { kInt, kVec } type;
union {
int i;
std::vector<Obj> v;
};
Obj& operator=(const Obj& o) { ... }
};
在这种情况下,由于递归引用,编译器会提示尝试使用不完整的对象 Obj
。如何以干净的方式解决这个问题?
谢谢
最佳答案
这里不存在类型递归问题:vector
内部状态只有指向 valute_type 的指针成员。
我认为,如果您尝试遵循 stackoverflow 规则“How to create a minimal, complete and verifiable example,您肯定会找到答案。
在您在评论中提供的示例代码中,有许多编译器提示的错误:Obj 的复制构造函数被删除,析构函数也被删除,然后赋值运算符是私有(private)的等等......
我只是一一修正了错误,并得到了正确的代码示例,这是您可能找到的答案:
#include <iostream>
#include <vector>
using namespace std;
class Obj {
enum class Type { kInt, kVec } type;
union {
int i;
vector<Obj> v;
};
public:
Obj(const Obj& o):type{o.type}{
if (o.type==Type::kVec)
new (&v) vector<Obj>(o.v);
else
i=o.i;
}
Obj(Obj&& o):type{o.type}{
if (o.type==Type::kVec)
new (&v) vector<Obj>(std::move(o.v));
else
i=o.i;
}
~Obj(){ if (type==Type::kVec) v.~vector<Obj>();}
Obj& operator=(const Obj&o){
if (o.type==Type::kVec && type==Type::kVec){
v=o.v;
return *this;
}
if (type == Type::kVec) {
v.~vector();
}
switch (o.type) {
case Type::kInt:
i = o.i;
break;
case Type::kVec:
new (&v) vector<Obj>(o.v);
break;
}
type=o.type;
return *this;
}
};
int main() {
return 0;
}
关于c++ - 递归类型的判别 union ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48936701/
我必须在服务器上运行 Excel 并终止我正在使用 taskkill.exe 的 excel.exe 进程: System.Diagnostics.Process.Start("taskkill.ex
我是一名优秀的程序员,十分优秀!