I'm trying to understand what the following line does:
BStats stats = BStats();
The struct is defined as follows:
struct BStats
{
unsigned a;
unsigned b;
BStats& operator+=(const BStats& rhs)
{
this->a += rhs.a;
this->b += rhs.b;
return *this;
}
};
But I have no idea about what this line does. Is it calling the default constructor?
The expression BStats()
is described in the standard in 5.2.3/2:
The expression T(), where T is a simple-type-specifier (7.1.5.2) for a non-array complete object type or the (possibly cv-qualified) void type, creates an rvalue of the specified type, which is value-initialized.
That is, the expression creates an rvalue of Bstats
type that is value-initialized . In your particular case, value-initialization means that the two members of the BStats
struct will be set to zero.
Note that this is different than the behavior of calling the default-constructor that is mentioned in other answers, as the default constructor will not guarantee that the members are set to 0.
Just like any class, a struct has a default constructor automatically created by the compiler. In your case, BStats() simply calls the default constructor, although the explicit call is useless.
在C ++中,类和结构几乎相同(不同之处在于C ++结构是具有public作为默认属性的类,而类的属性是私有的),就像调用构造函数一样。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.