引用可能是指向结构的成员C++

Reference could be pointing struct's members in C++

本文关键字:结构 成员 C++ 引用      更新时间:2023-10-16

我们是否可以创建一个包含一些值和指向同一结构中的值的引用的结构?我的想法是用假名。所以我可以用不同的方式调用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)
    {
    }
};

谢谢大家。

NB:我用指针做了,但是现在当我试图调用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大小(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将提供更好的封闭。私有数据成员和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;
}

使用解引用运算符取值:*(size4.minx)

一个小例子:

Size4 sz(11, 2, 3, 4);
printf("%f, %f, %f, %f", *sz.minX, *sz.maxX, *sz.minY, *sz.maxY);