在c ++中初始化结构的成员变量 [英] Initializing member variables of a struct in c++
本文介绍了在c ++中初始化结构的成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有一些double值的结构:
I have a struct with a few double values:
struct A {
double a;
double b;
}
A a
都是在C ++中自动初始化为零的成员(例如 aa
)?
if I create a new struct, e.g. A a
, are all the members (e.g. a.a
) initialized to zeroes automatically in C++?
推荐答案
不是默认情况下(除非是静态存储的变量 - 也就是 static
全局变量)。
Not by default (unless it's a variable of static storage - that is, a static
or global variable).
有几种方法可以将这种结构初始化为zeros:
There are a few ways to initialize a struct of this kind to "zeros":
A a = { 0.0, 0.0 };
A a = { };
A a = A();
或如果您有一个C ++ 11兼容的编译器:
or if you have a C++11 compatible compiler:
A a{0.0, 0.0};
A a{}
或者添加一个构造函数到 struct
定义:
or add a constructor to the struct
definition:
struct A {
double a;
double b;
A() : a(0.0), b(0.0) {}
};
这篇关于在c ++中初始化结构的成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文