在阅读一篇文章时,我看到了以下功能:
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,
};
}作者在用返回语句做什么?我以前从没见过这样的东西,我也不知道怎么去找.对普通C也有效吗?
编辑:link to the original article
发布于 2015-07-23 17:30:12
这是无效的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;
}最大的区别(如您所看到的)是,指定的初始化器允许您使用成员名来指定初始化器流向哪个成员,而不只是依赖于顺序/位置。
发布于 2015-07-23 17:22:08
这是一个C99 compound literal。这个特性是C99特有的,但是gcc和clang也选择在C++中实现它(比如extension)。
6.26复音字 ISO C99支持复合文字。复合文字看起来像包含初始化器的强制转换。它的值是在强制转换中指定的类型的对象,包含在初始化器中指定的元素;它是一个lvalue。作为一种扩展,GCC在C90模式和C++模式下都支持复合文本,但在C++中语义有一些不同。
https://stackoverflow.com/questions/31594037
复制相似问题