[英]Using struct name as a function
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: 在5.2.3 / 2中的标准中描述了表达式BStats()
:
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. 表达式T(),其中T是非数组完整对象类型或(可能是cv限定的)void类型的简单类型说明符(7.1.5.2),将创建指定类型的右值,即value -初始化。
That is, the expression creates an rvalue of Bstats
type that is value-initialized . 也就是说,该表达式将创建一个Bstats
类型的右值 ,该值已初始化为value 。 In your particular case, value-initialization means that the two members of the BStats
struct will be set to zero. 在您的特定情况下, 值初始化意味着BStats
结构的两个成员将被设置为零。
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. 请注意,这与调用其他答案中提到的default-constructor的行为不同,因为默认构造函数将无法保证将成员设置为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. 在您的情况下,BStats()仅调用默认构造函数,尽管显式调用没有用。
在C ++中,类和结构几乎相同(不同之处在于C ++结构是具有public作为默认属性的类,而类的属性是私有的),就像调用构造函数一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.