我们是否可以创建一个包含一些值和指向同一结构中值的引用的结构?我的想法是制作别名。所以我可以用不同的方式调用struct成员!
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;和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;
但是,
class
将提供更好的封装。私有(private)数据成员和get-er函数访问minX
。[编辑]
像这样使用
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;
}