gpt4 book ai didi

c++ - C++ POD 类型不能有任何构造函数吗?

转载 作者:IT老高 更新时间:2023-10-28 22:12:24 35 4
gpt4 key购买 nike

我有一个类和一个 const 变量。

struct A 
{
int b;
};

A const a;

A类是POD,可以这样初始化。

A const a = { 3 };

恕我直言,拥有这样的构造函数看起来不错。

struct A 
{
int b;

A(int newB) : b(newB)
{
}
};

但 Clang 假定 A 为非聚合类型。为什么我不能有这样的构造函数?还是我应该做点别的?


我修改了问题以表达我原来的意思。我错误地将 struct 写为 class,对于 @Johannes 的混淆感到抱歉:)

最佳答案

POD 表示普通旧数据类型,根据定义不能有用户定义的构造函数。

POD 实际上是一个聚合类型(见下一段引文)。那么什么是聚合? C++ 标准在第 8.5.1/1 节中说,

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected nonstatic data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

C++ 标准的第 9/4 节说,

[....] A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor. Similarly, a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor. A POD class is a class that is either a POD-struct or a POD-union.

由此可见,POD 类/结构/union 虽然不能有用户定义的赋值操作符用户定义的析构函数


不过,还有其他类型的 POD。第 3.9/10 节说,

Arithmetic types (3.9.1), enumeration types, pointer types, and pointer to member types (3.9.2), and cv-qualified versions of these types (3.9.3) are collectively called scalar types. Scalar types, POD-struct types, POD-union types (clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called POD types.

阅读此常见问题解答:What is a "POD type"?

关于c++ - C++ POD 类型不能有任何构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5442717/

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