[英]Constructor for Struct with Private Members
Consider the following code: 请考虑以下代码:
class A
{
private:
struct B { private: int i; friend class A; };
public:
static void foo1()
{
B b;
b.i = 0;
}
static void foo2()
{
B b = {0};
}
};
Why does foo1 work but not
foo2 ?
为什么foo1工作但不是
foo2 ? Is not the struct initializer constructor visible for class A?
对于类A,结构化初始化器构造函数是否可见? Is there anyway to make this work in C++11?
反正有没有在C ++ 11中使这个工作?
(Note, removing the private makes foo2 working.) (注意,删除私有使foo2工作。)
Why does
foo1
work but notfoo2
?为什么
foo1
工作但不是foo2
? Is not the struct initializer constructor visible for classA
?对于类
A
,结构化初始化器构造函数是否可见?
B b = {0};
Does not work because B
is not an Aggregate . 不起作用,因为
B
不是聚合 。 And it is not an Aggregate because it has an non-static private data member. 并且它不是聚合,因为它具有非静态私有数据成员。 If you remove the private specifier,
B
becomes an Aggregate and hence can be initialized in this manner. 如果删除私有说明符,则
B
成为聚合,因此可以以这种方式初始化。
C++03 Standard 8.5.1 Aggregates C ++ 03标准8.5.1聚合
Para 7: 第7段:
If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized (8.5).
如果列表中的初始值设定项少于聚合中的成员,则未明确初始化的每个成员都应进行值初始化(8.5)。 [Example:
[例:
struct S { int a; char* b; int c; }; S ss = { 1, "asdf" };
initializes
ss.a
with1
,ss.b
with"asdf"
, andss.c
with the value of an expression of the formint()
, that is,0
.初始化
ss.a
与1
,ss.b
与"asdf"
,和ss.c
与以下形式的表达式的值int()
即,0
。 ]]
C++03 standard 8.5.1 §1 : C ++ 03标准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 non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).
聚合是一个数组或类(第9节),没有用户声明的构造函数(12.1), 没有私有或受保护的非静态数据成员 (第11节),没有基类(第10节),没有虚函数(10.3) )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.