如何将联合发送到函数

时间:2018-03-15 20:02:28

标签: c++

time_spent

如何将void init()传递给drawing::time_spent.hours作为函数的参数? drawing::time_spent无法正常工作,只是简单地说"期待a)"。如果我只使用[ { "hierarchy" : ["obj1"], "prop1":"value" }, { "hierarchy" : ["obj1","obj2"], "prop2":"value", "prop3":"value" }, { "hierarchy" : ["obj1","obj3"], "prop4":"value", "prop5":"value" }, { "hierarchy" : ["obj1","obj3", "obj4"], "prop6":"value", "prop7":"value", "arr" :["val1", "val2"] } ] ,我就无法为其指定任何内容,它会说"不存在合适的构造函数"。

该计划实际上不应该做任何事情,我只想表明我理解工会,但我显然根本不理解它们。

1 个答案:

答案 0 :(得分:5)

您不能单独传递time_spent,因为init()需要指向drawing结构的指针,而不是指向union的指针,例如:

drawing d;
init(&d);

此外,无论如何,您的union未正确宣布。您只是声明一个名为time_spent嵌套类型,但您没有使用该类型声明任何 struct field 。如果你想要一个名为time_spent的结构字段,那么union应该是这样的:

struct drawing {
    int some_variable;
    union
    {
        int seconds;
        float minutes;
        float hours;
    } time_spent; // How much time was spent on it
};

它声明了一个名为time_spent的结构字段,它是一个匿名联合类型。

或者,将union声明与struct声明分开:

union u_time {
    int seconds;
    float minutes;
    float hours;
};

struct drawing {
    int some_variable;
    u_time time_spent; // How much time was spent on it
};

无论哪种方式,init()都可以time_spent访问my_drawing->time_spent字段。