gpt4 book ai didi

c++ - 使用用户定义的构造函数对非聚合类进行值初始化

转载 作者:行者123 更新时间:2023-11-30 02:59:50 27 4
gpt4 key购买 nike

我正在回答这个问题:Aggregates and pods当 C++ 中具有用户定义的默认构造函数的类的对象仅初始化了其中的一些数据成员时,其余数据成员是否会被值初始化?以下是我尝试导致编译错误的程序:

#include <iostream>
using namespace std;

class A {
public:
A() {
i=10;
f = 10.0f;
c = 45;
d = 10.0;
}

void show() {
cout << i << "\t" << f << "\t" << c << "\t" << d<<"\n";
}

private:
int i;
float f;
char c;
double d;
};

int main() {
A a={20,20.0f};
a.show();
}

最佳答案

您的类不符合聚合条件,因为它具有私有(private) 非静态数据成员。

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

编辑:

For objects of non aggregate classes if only some of the data members are initialized, will the rest be value initialized(assigned with 0)?

规则在:

C++11 8.5.4 列表初始化 [dcl.init.list] 第 3 段:

List-initialization of an object or reference of type T is defined as follows:
— If the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.
— Otherwise, if T is an aggregate, aggregate initialization is performed (8.5.1).
— Otherwise, if T is a specialization of std::initializer_list, an initializer_list object is constructed as described below and used to initialize the object according to the rules for initialization of an object from a class of the same type (8.5).
— Otherwise, if T is a class type, constructors are considered. The applicable constructors are enumerated and the best one is chosen through overload resolution (13.3, 13.3.1.7). If a narrowing conversion (see below) is required to convert any of the arguments, the program is ill-formed.
— Otherwise, if T is a reference type, a prvalue temporary of the type referenced by T is list-initialized, and the reference is bound to that temporary. [ Note: As usual, the binding will fail and the program is ill-formed if the reference type is an lvalue reference to a non-const type. —end note ]
— Otherwise, if the initializer list has a single element, the object or reference is initialized from that element; if a narrowing conversion (see below) is required to convert the element to T, the program is ill-formed.
— Otherwise, if the initializer list has no elements, the object is value-initialized.
— Otherwise, the program is ill-formed.

您的程序不属于上述任何一种情况,因此属于格式错误的情况。

关于c++ - 使用用户定义的构造函数对非聚合类进行值初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12596158/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com