c++ - 引用可以指向 C++ 中的结构成员

标签 c++ pointers struct reference

我们可以创建一个包含一些值的结构和指向同一结构中的值的引用吗?我的想法是制作别名。所以我可以用不同的方式调用结构成员!

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/

相关文章:

c - 在 C 中是否以这种方式释放结构?

c++ - 从 C 到 C++ 的常量结构中的 char 数组的静态初始化

c++ - 是否有一些用于模拟 Glib::Dispatcher 的 Boost 功能?

c - 地址上的二维 float 组

c++ - 使用 decltype 从指针推导类型

c++ - 我怎样才能安全地将 float *x 变成 const float *const *y?

c - 访问数组段错误中的数据

c - 使用Struct和指针的程序中的不确定性(C语言程序)

c++ - 为具有特定字段的成员搜索通用范围

android - 如何将 WCHAR_T* 转换为 jstring?