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, ... }
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01