C++ 初始化类的结构数据成员
只需在结构定义中添加构造函数即可:C++ 初始化类的结构数据成员,c++,C++,只需在结构定义中添加构造函数即可: typedef struct _MY_STRUCT { std::string mystring; int n1; int n2; } MY_STRUCT; class foo { public: foo(): m_mystruct() { } private: MY_STRUCT
typedef struct _MY_STRUCT
{
std::string mystring;
int n1;
int n2;
} MY_STRUCT;
class foo
{
public:
foo():
m_mystruct()
{ }
private:
MY_STRUCT m_mystruct;
};
int main(void)
{
foo oFoo;
// Why doesnt this intialize all data members of foo to NULL/0.
// what is the correct way to get all members of MY_STRUCT to be intialized to NULL/0.
}
首先,你不需要在C++中这样做<代码> TyPulf< /Cord>。其次,为您的结构创建默认构造函数:
typedef struct _MY_STRUCT
{
_MY_STRUCT()
{
n1 = 0;
n2 = 0;
}
std::string mystring;
int n1;
int n2;
} MY_STRUCT;
这样,结构成员将默认初始化为:
到空字符串(通过其默认构造函数)std::string
s归零int
struct MY_STRUCT
{
std::string mystring;
int n1;
int n2;
MY_STRUCT() : mystring(), n1(), n2() {}
};
原因很可能是你使用VisualC++。即使在版本10中,Visual C++也不正确地进行值初始化。您的代码在g++4.4.1中运行良好 <> 2005左右,Visual C++不太符合标准,因为C++中的C++ 98规则初始化是改变的。这是C++03中唯一的语言更改,否则它只是C++98的“技术勘误表”(C++03有时被称为TC1,技术勘误表1)。C++03引入了“值初始化”作为“默认初始化”的泛化,以使结果不那么随意、不那么令人费解,并且对于像您这样的聚合类(同时包含POD和非POD成员的类)更实用:根据C++03规则,这些成员是零初始化或默认初始化的(视情况而定),都是。这是一件非常好的事情。这是Andrew Koenig提出的,IIRC,它加重了他对Koenig查找的指责(又称ADL,参数依赖查找)。:-)
但是,2010的情况下,VisualC++无法正确地理解这一点有点不可理解。 也就是说,您的代码很糟糕。:-)
参见其他改进代码的注释,包括定义构造函数的想法,这将解决VisualC++的问题。
干杯,还有其他方法可以做到这一点,但现在这已经足够好了。@anonymous downvoter:请解释你的downvote;它看起来特别死气沉沉。很可能您不熟悉值初始化。我建议你查一下。
MY_STRUCT ms;
assert( ms.mystring.empty());
assert( ms.n1 == 0 );
assert( ms.n2 == 0 );