在C ++中初始化结构体 [英] Initializing structs in C++

查看:165
本文介绍了在C ++中初始化结构体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为此问题的补充,这里发生了什么:

As an addendum to this question, what is going on here:

#include <string>
using namespace std;

struct A {
    string s;
};

int main() {
    A a = {0};
}

显然,您不能将std :: string设置为零。有人可以提供一个解释(支持参考C ++标准,请)关于实际应该发生在这里?然后解释例子):

Obviously, you can't set a std::string to zero. Can someone provide an explanation (backed with references to the C++ Standard, please) about what is actually supposed to happen here? And then explain for example):

int main() {
    A a = {42};
}

这两个是否都很好定义?

Are either of these well-defined?

对我来说一个令人尴尬的问题 - 我总是给我的structs构造函数,所以这个问题从来没有出现过。

Once again an embarrassing question for me - I always give my structs constructors, so the issue has never arisen before.

推荐答案

您的结构是一个聚合,所以聚合初始化的普通规则对它起作用。该过程在8.5.1中描述。基本上整个8.5.1是专门为它,所以我没有看到理由在这里复制整个东西。一般的想法是几乎一样的C,只是适应C ++:你从右边的初始化,你从左边取一个成员,你用该初始化器初始化成员。根据8.5 / 12,这将是一个复制初始化

Your struct is an aggregate, so the ordinary rules for aggregate initialization work for it. The process is described in 8.5.1. Basically the whole 8.5.1 is dedicated to it, so I don't see the reason to copy the whole thing here. The general idea is virtually the same it was in C, just adapted to C++: you take an initializer from the right, you take a member from the left and you initialize the member with that initializer. According to 8.5/12, this shall be a copy-initialization.

当你做

A a = { 0 };

你基本上是以 0 ,即 as 它在语义上等同于

you are basically copy-initializing a.s with 0, i.e. for a.s it is semantically equivalent to

string s = 0;

上述编译是因为 std :: string 可以从 const char * 指针转换。 (这是未定义的行为,因为空指针在这种情况下不是有效的参数。)

The above compiles because std::string is convertible from a const char * pointer. (And it is undefined behavior, since null pointer is not a valid argument in this case.)

您的 42 版本将不会编译为同样的原因

Your 42 version will not compile for the very same reason the

string s = 42;

无法编译。 42 不是空指针常数, std :: string 没有从 int 类型。

will not compile. 42 is not a null pointer constant, and std::string has no means for conversion from int type.

PS >在C ++中不是递归的(例如,与POD的定义相反)。 std :: string 不是一个聚合,但它不会改变你的 A 的任何东西。 A 仍为汇总。

P.S. Just in case: note that the definition of aggregate in C++ is not recursive (as opposed to the definition of POD, for example). std::string is not an aggregate, but it doesn't change anything for your A. A is still an aggregate.

这篇关于在C ++中初始化结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆