C ++成员变量别名?

编程入门 行业动态 更新时间:2024-10-24 04:51:51
本文介绍了C ++成员变量别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我很确定这是可能的,因为我确定我已经看到了它。我认为这是真棒,但我会很乐意接受这是一个可怕的想法,因为____的答案。

I'm pretty sure this is possible, because I'm pretty sure I've seen it done. I think it is awesome, but I will gladly accept answers along the lines of "this is a terrible idea because ____".

假设我们有一个基本的结构。 p>

Say we have a basic struct.

struct vertex { float x, y, z; };

现在,我想对这些变量实现别名。

Now, I want to implement aliases on these variables.

vertex pos; vertex col; vertex arr; pos.x = 0.0f; pos.y = 0.5f; pos.z = 1.0f; col.r = 0.0f; col.g = 0.5f; col.b = 1.0f; arr[0] = 0.0f; arr[1] = 0.5f; arr[2] = 1.0f;

理想情况下,第三种语法与数组不可区分。也就是说,如果我发送 arr 作为参数参数到一个函数,期望一个浮点数组,它将存储数据(例如许多OpenGL glGet 函数),它会工作得很好。

Ideally the third syntax would be indistinguishable from an array. That is, if I sent arr as a reference parameter to a function expecting an array of floats into which it will store data (eg many of the OpenGL glGet functions), it would work fine.

你觉得怎么样?可能?

What do you think? Possible? Possible but stupid?

推荐答案

我会做的是让访问者:

struct Vertex { float& r() { return values[0]; } float& g() { return values[1]; } float& b() { return values[2]; } float& x() { return values[0]; } float& y() { return values[1]; } float& z() { return values[2]; } float operator [] (unsigned i) const { return this->values_[i]; } float& operator [] (unsigned i) { return this->values_[i]; } operator float*() const { return this->values_; } private: float[3] values_; }

更多推荐

C ++成员变量别名?

本文发布于:2023-07-29 08:46:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239201.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:别名   变量   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!