簡體   English   中英

C ++中的奇怪語法:return {.name = value,...}

[英]Odd syntax in C++: return { .name=value, … }

在閱讀文章時,我遇到了以下功能:

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也有效嗎?

編輯: 鏈接到原始文章

這不是有效的C ++。

它是(某種程度上)使用C中的一些特性,稱為“復合文字”和“指定初始化器”,一些C ++編譯器支持它作為擴展。 “有點”來自於這樣一個事實:要成為一個合法的C復合文字,它應該具有看起來像一個演員的語法,所以你有類似的東西:

return (RasterInfo) {
    .offset = 0,
    .length = 1,
    .stretch_cycles = (_width - 1) * 4,
    .repeat_lines = 1000,
  };

然而,無論語法有何不同,它基本上都是創建一個臨時結構,其成員按塊中的指定進行初始化,因此大致相當於:

// 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;
}

最大的區別(如您所見)是指定的初始化程序允許您使用成員名稱來指定初始化程序轉到哪個成員,而不是僅僅依賴於順序/位置。

這是一個C99 復合文字 此功能特定於C99,但gcc和clang也選擇在C ++中實現它(作為擴展名 )。

6.26復合文字

ISO C99支持復合文字。 復合文字看起來像包含初始值設定項的強制轉換。 它的值是轉換中指定類型的對象,包含初始值設定項中指定的元素; 這是一個左值。 作為擴展,GCC支持C90模式和C ++中的復合文字,盡管語義在C ++中有些不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM