gpt4 book ai didi

c++ - 具有私有(private)成员的结构的构造函数

转载 作者:行者123 更新时间:2023-11-30 02:58:42 26 4
gpt4 key购买 nike

考虑以下代码:

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};
}
};

为什么 foo1 有效而 foo2 无效?类 A 的结构初始化构造函数不是可见的吗?有没有办法在 C++11 中完成这项工作?

(注意,删除 private 使 foo2 工作。)

最佳答案

Why does foo1 work but not foo2? Is not the struct initializer constructor visible for class A?

B b = {0};

不起作用,因为 B 不是聚合。而且它不是聚合,因为它有一个非静态私有(private)数据成员。如果删除私有(private)说明符,B 将成为聚合,因此可以以这种方式进行初始化。


C++03 标准 8.5.1 聚合
第 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). [Example:

 struct S { int a; char* b; int c; };
S ss = { 1, "asdf" };

initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is,0. ]

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).

关于c++ - 具有私有(private)成员的结构的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13551572/

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