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

查看:12
本文介绍了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天全站免登陆