更新结构中的变量

Updating a variable in a struct

所以我刚刚创建了一个构成矩形的结构。结构本身看起来像这样

    struct _rect
{
    //bottom left vertex
    int x = 0;
    int y = 0;

    // width and height 
    int width = 0;
    int height = 0;

    //top right vertex
    int y2 = y + height;
    int x2 = x + width; 
};

//init rect
_rect rect01;
rect01.x = rect01.y = 50;
rect01.width = rect01.height = 200;

在主cpp中,当我想创建它的一个实例时,我只想输入左下角的x和y,加上宽度和高度,我想让它自己计算右上角的顶点,有没有办法无需手动分配 x2 和 y2 的值​​?

您应该创建一个特定的 class:

class Rect
{
public:
  Rect(int x, int y, unsigned int width, unsigned int height)
  : m_x(x), m_y(y), m_width(width), m_height(height)
  {}

  int x() { return m_x; }
  int y() { return m_y; }
  int top() { return m_y + m_height; }
  int right() { return m_x + m_width; }

private:
  int m_x;
  int m_y;
  unsigned int m_width;
  unsigned int m_height;
};

这使您可以在 class 方法中进行所需的计算。 如果需要,您还可以创建 setter 和更多 getter。

下面是完整的工作示例

#include <iostream>
class Rect
{
public:
  //parameterized constructor 
  Rect(int px, int py, unsigned int pwidth, unsigned int pheight): x(px), y(py), width(pwidth), height(pheight), x2(x + width), y2(y + height)
  {
    
    
   
  };
  
  //getter so that we can get the value of x2 
  int getX2()
  {
      return x2;
  }
  //getter so that we can get the value of y2 
  int getY2()
  {
      return y2;
  }

private:
  int x = 0;
  int y = 0;
  unsigned int width = 0;
  unsigned int height = 0;
  
  int x2 = 0, y2 = 0;
};

int main()
{
    //create Rect instance
    Rect r(50, 50, 200, 200);
    //lets check if x2 and y2 were calculate correctly
    std::cout<<"x2 is: "<< r.getX2()<<std::endl;
    std::cout<<"y2 is: "<< r.getY2()<<std::endl;
}

上面程序的输出可见here.