我们可以创建一个包含一些值的结构和指向同一结构中的值的引用吗?我的想法是制作别名。所以我可以用不同的方式调用结构成员!
struct Size4
{
float x, y;
float z, w;
float &minX, &maxX, &minY, &maxY;
Size4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w),
minX(x), maxY(y), minY(z), maxY(w)
{
}
};
谢谢大家
注意:我是用指针完成的,但现在当我尝试调用 Size4.minX()
时,我得到的是地址,而不是值。
struct Size4
{
float x, y;
float z, w;
float *minX, *maxX, *minY, *maxY;
Size4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w),
minX(&x), maxX(&y), minY(&y), maxY(&w)
{
}
};
最佳答案
“我想让它透明。Size4 size(5,5,5,5); size.minX; and size.x; 返回相同的值...”
你可以这样做。但是,我建议您使用 class
。
using namespace std;
struct Size4
{
float x, y;
float z, w;
float *minX, *maxX, *minY, *maxY;
Size4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w),
minX(&x), maxX(&y), minY(&y), maxY(&w)
{
}
};
int main() {
Size4 s(1,2,3,4);
std::cout << *(s.minX) << std::endl;
return 0;
}
或者您可以将此方法添加到您的struct
float getX() {
return *minX;
}
并像这样访问它:
std::cout << s.getX() << std::endl;
但是,类
会提供更好的外壳。访问 minX
的私有(private)数据成员和 get-er 函数。
[编辑]
使用 class
很简单,如下所示:
#include <iostream>
using namespace std;
class Size4
{
private:
// these are the private data members of the class
float x, y;
float z, w;
float *minX, *maxX, *minY, *maxY;
public:
// these are the public methods of the class
Size4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w),
minX(&x), maxX(&y), minY(&y), maxY(&w)
{
}
float getX() {
return *minX;
}
};
int main() {
Size4 s(1,2,3,4);
std::cout << s.getX() << std::endl;
// std::cout << *(s.minX) << std::endl; <-- error: ‘float* Size4::minX’ is private
return 0;
}
关于c++ - 引用可以指向 C++ 中的结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23724108/