Odd syntax in C++: return { .name=value, ... }(C++ 中的奇怪语法:return { .name=value, ... })
问题描述
在阅读一篇文章时,我遇到了以下功能:
While reading an article, I came across the following function:
SolidColor::SolidColor(unsigned width, Pixel color)
: _width(width),
_color(color) {}
__attribute__((section(".ramcode")))
Rasterizer::RasterInfo SolidColor::rasterize(unsigned, Pixel *target) {
*target = _color;
return {
.offset = 0,
.length = 1,
.stretch_cycles = (_width - 1) * 4,
.repeat_lines = 1000,
};
}
作者对return语句做了什么?我以前没见过这样的东西,我不知道如何搜索它......它对普通C也有效吗?
What is the author doing with the return statement? I haven't seen anything like that before, and I do not know how to search for it... Is it valid for plain C too?
原文链接
推荐答案
这不是有效的 C++.
This isn't valid C++.
它(在某种程度上)使用了 C 中的几个特性,称为复合文字"和指定初始化程序",一些 C++ 编译器支持这些特性作为扩展.某种"来自这样一个事实,即作为一个合法的 C 复合文字,它应该具有看起来像强制转换的语法,所以你会有类似的东西:
It's (sort of) using a couple features from C known as "compound literals" and "designated initializers", which a few C++ compilers support as an extension. The "sort of" comes from that fact that to be a legitimate C compound literal, it should have syntax that looks like a cast, so you'd have something like:
return (RasterInfo) {
.offset = 0,
.length = 1,
.stretch_cycles = (_width - 1) * 4,
.repeat_lines = 1000,
};
然而,不管语法上的不同,它基本上是创建一个临时结构,其成员按照块中的指定初始化,所以这大致相当于:
Regardless of the difference in syntax, however, it's basically creating a temporary struct with members initialized as specified in the block, so this is roughly equivalent to:
// A possible definition of RasterInfo
// (but the real one might have more members or different order).
struct RasterInfo {
int offset;
int length;
int stretch_cycles;
int repeat_lines;
};
RasterInfo rasterize(unsigned, Pixel *target) {
*target = color;
RasterInfo r { 0, 1, (_width-1)*4, 1000};
return r;
}
最大的区别(如您所见)是指定初始化器允许您使用成员名称来指定初始化器用于哪个成员,而不是仅取决于顺序/位置.
The big difference (as you can see) is that designated initializers allow you to use member names to specify what initializer goes to what member, rather than depending solely on the order/position.
这篇关于C++ 中的奇怪语法:return { .name=value, ... }的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 中的奇怪语法:return { .name=value, ... }


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01