我有一些代码有点像这样:
class Token{
public:
union tester{
double literal;
string name;
tester(double op) : literal(op) {};
tester(string val) : name(val) {};
tester(): tester(0.0) {};
};
void setUp(){
//the literal and name members of tester should be initialized here
};
/*other functions are below, two of which require that the values of literal
and name can be changed*/
};
我需要同时初始化文字和名称成员,但我不确定如何初始化。我尝试制作一个类型为 tester 的变量并执行此操作:tester test(45.0);,但是我只能设置其中一个成员变量,并且只需使用 tester(45.0);也不起作用我试过这个: token 的东西; thing.name = "Elly",那没用。我的类(class)也不使用构造函数。所以,我的问题是,如何在 Token 中设置然后更改测试器中的成员变量的值?
我正在使用 C++11 编译器。
(如果这个问题已经被回答或者太愚蠢,我提前道歉,我一直在四处寻找,但我真的不明白我怎么能让这个工作。我错过了一些东西,但我'我不太确定是什么。)
最佳答案
简而言之:不要这样做。
当表示具有相同二进制表示的数据时, union 最适合使用,例如:
union v4f {
float f[4];
struct {
float x;
float y;
float z;
float t;
};
};
v4f v;
v.f[1] = 2.f;
v.t = 0.f;
假设您确实想在这里使用一个 union ,而不是一个结构,即一个标记包含一个名称或一个文字,但绝不会同时包含这两者,并且您确实需要节省额外的存储空间结构将花费:
在 C++11 之前,您不能拥有具有非平凡析构函数的 union 成员,例如您的 tester.name
字符串字段。参见 this question了解更多详情。
现在,这是可能的,但我建议您不要这样做,除非您真的知道发生了什么。为此,您需要定义 union 的析构函数,因为编译器无法决定要删除哪个非平凡的 union 成员。我认为您最好避免这种情况,因为如果没有任何其他信息,这不是一个容易回答的问题:
~tester() {
// delete name member or not ?
// very hard to decide without additional data
}
至于如何访问你的union成员,因为你的union不是匿名的,所以不能匿名访问,所以你需要实际创建一个你类的成员,并引用这个类成员。
class Token {
public:
union tester {
double literal;
string name;
tester(double op) : literal(op) {};
tester(string val) : name(val) {};
tester(): tester(0.0) {};
~tester() {}
};
tester data;
...
};
...
Token t;
t.data.name = "Elly";
关于c++ - 如何在命名 union 中使用构造函数?以及以后如何更改同一 union 实例中的值? C++/C++11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21808695/