gpt4 book ai didi

c++ - 嵌套结构构造函数和 Union 的问题

转载 作者:行者123 更新时间:2023-11-30 02:03:41 25 4
gpt4 key购买 nike

我在类中有一个嵌套的结构和该结构的 union 。如果我有一个接受参数的结构构造函数,那么 union 将不会编译。

我还想使用参数创建结构的实例。该行也失败了。

class test
{
public:
test(void);
~test(void);

struct dtType {
// inline constructors with initialisation lists
dtType() : mins(0), hrs(0),day(0),mnth(0),year(0),DPOffset(0),DTType(0) {}
dtType(byte z) : mins(z), hrs(z),day(z),mnth(z),year(z),DPOffset(0),DTType(0) {}
dtType(byte n,byte h, byte d, byte m, byte y, byte o, byte t) : mins(n), hrs(h),day(d),mnth(m),year(y),DPOffset(o),DTType(t) {}

// overloaded operator functions
bool operator< (dtType date){return true;};
bool operator<= (dtType date){return true;};
bool operator> (dtType date){return true;};
bool operator>= (dtType date){return true;};
bool operator== (dtType date){return true;};

// data members
unsigned mins: 3;
unsigned hrs: 5; // 8 bits
unsigned day: 5;
unsigned mnth: 4;
unsigned year: 7; // 16 bits
unsigned DPOffset: 6;
unsigned DTType : 2;
};

// if I comment out the union it compiles, otherwise I get:
// error C2620: member 'test::dtUnion::dt' of union 'test::dtUnion' has user-defined constructor or non-trivial default constructor

union dtUnion {
dtType dt;
unsigned long dtLong; // 32 bits
} dtU;

// if I call dtType judgement_day(); it compiles. Otherwise I get:
dtType judgement_day(1); // error C2059: syntax error : 'constant'

};

按照下面的答案,我现在尝试了以下方法,但出现错误 C2438:judgement_day,dateMask,timeMask : cannot initialize static class data via constructor

class test
{
public:
test(): judgement_day(1),dateMask(1,1,1,1,1,0,0),timeMask(1,1,0,0,0,0,0){}
~test();
public:
struct dtType {
// inline constructors with initialisation lists
dtType() : mins(0), hrs(0),day(0),mnth(0),year(0),DPOffset(0),DTType(0) {}
dtType(byte z) : mins(z), hrs(z),day(z),mnth(z),year(z),DPOffset(0),DTType(0) {}
dtType(byte n,byte h, byte d, byte m, byte y, byte o, byte t) : mins(n), hrs(h),day(d),mnth(m),year(y),DPOffset(o),DTType(t) {}
// overloaded operator functions
bool operator< (dtType date){return true;};
bool operator<= (dtType date){return true;};
bool operator> (dtType date){return true;};
bool operator>= (dtType date){return true;};
bool operator== (dtType date){return true;};
// data members
unsigned mins: 3;
unsigned hrs: 5; // 8 bits
unsigned day: 5;
unsigned mnth: 4;
unsigned year: 7; // 16 bits
unsigned DPOffset: 6;
unsigned DTType : 2;
};
const static dtType judgement_day;
const static dtType dateMask;
const static dtType timeMask;
};

最佳答案

标准不允许让 union 成员具有显式构造函数,这与 union 是成员还是嵌套类型无关。

以下也会编译失败:

struct X
{
X() {};
};
union Y
{
X k;
};

关于c++ - 嵌套结构构造函数和 Union 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11520000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com