我有这样的结构:
struct Snapshot
{
double x;
int y;
};
我想让x和y等于0。它们是默认为0还是我必须这样做:
Snapshot s = {0,0};
还有什么方法可以把结构归零呢?
我有这样的结构:
struct Snapshot
{
double x;
int y;
};
我想让x和y等于0。它们是默认为0还是我必须这样做:
Snapshot s = {0,0};
还有什么方法可以把结构归零呢?
当前回答
在c++中,使用无参数构造函数。在C语言中,你不能有构造函数,所以使用memset或者——有趣的解决方案——指定初始化器:
struct Snapshot s = { .x = 0.0, .y = 0.0 };
其他回答
在c++中,使用无参数构造函数。在C语言中,你不能有构造函数,所以使用memset或者——有趣的解决方案——指定初始化器:
struct Snapshot s = { .x = 0.0, .y = 0.0 };
一般来说,没有。然而,在函数/中声明为文件作用域或静态作用域的结构体将被初始化为0(就像那些作用域的所有其他变量一样):
int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0
void foo() {
struct { int a, b; } bar; // undefined
static struct { int c, d; } quux; // 0, 0
}
我相信正确的答案是它们的值是没有定义的。通常,在运行调试版本的代码时,它们被初始化为0。在运行发布版本时通常不是这样。
将pod成员移动到基类以缩短初始化列表:
struct foo_pod
{
int x;
int y;
int z;
};
struct foo : foo_pod
{
std::string name;
foo(std::string name)
: foo_pod()
, name(name)
{
}
};
int main()
{
foo f("bar");
printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}
有了POD,你也可以写作
Snapshot s = {};
你不应该在c++中使用memset, memset有一个缺点,如果结构中有一个非pod,它会破坏它。
或者像这样:
struct init
{
template <typename T>
operator T * ()
{
return new T();
}
};
Snapshot* s = init();