C ++中的奇数语法:return {.name = value,...} [英] Odd syntax in C++: return { .name=value, ... }

查看:44
本文介绍了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,...}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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