gpt4 book ai didi

c++ - 在 C++11 中返回可变值

转载 作者:太空宇宙 更新时间:2023-11-04 14:38:12 24 4
gpt4 key购买 nike

我想知道如何让一个方法返回一个右值。具体来说,我想知道是否有办法使用重载运算符来执行此操作。我有这段代码:

struct vec4 {
float x;
float y;
float z;
float w;
...
inline float operator [] (int i)
{
switch (i) {
case 0:
return this->x;
case 1:
return this->y;
case 2:
return this->z;
case 3:
return this->w;
default:
exit(1);
return 0;
}
}
};

我怎样才能改变这个,这样我就可以使用一些东西来达到

vec4 v;
...
v[2] = 5.0f;

我听说过 C++11 中的右值引用,它们可能是一个潜在的解决方案吗?

编辑:我找到了一种放入我的实际代码的方法。

最佳答案

为此不需要 C++11。只需:

float & operator[](std::size_t i) { return data[i]; }

现在你可以说 v[2] = 5; 一切都很好。

如果需要,您可以添加一个不使用引用且可用于读取值的常量重载。

float operator[](std::size_t i) const { return data[i]; }

您唯一可能考虑使用右值成员函数限定符的情况是您希望允许将分配给一个临时成员:

vec4{}[2] = 5;

在那种情况下,你仍然返回一个左值引用,但你必须限定成员函数:

float & operator[](std::size_t i) && { return data[i]; }
// ^^^^

关于c++ - 在 C++11 中返回可变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14103911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com