Is there a way of applying a function to each member of a struct in c++?

后端 未结 13 1079
轻奢々
轻奢々 2021-01-13 02:31

You have a simple struct, say:

typedef struct rect
{
    int x;
    int y;
    int width;
    int height;
}
rect;

And you want to multiply

13条回答
  •  既然无缘
    2021-01-13 03:19

    Like everyone has said, you can't do it directly, but there's nothing stopping you from overloading the * operator:

    struct rect 
    { 
       int x; 
       int y; 
       int width; 
       int height; 
    }
    
    rect operator*(const rect& r, int f)
    {
      rect ret=r;
      ret.x*=f;
      ret.y*=f;
      ret.width*=f;
      ret.height*=f;
      return ret;
    }
    

    then you can do this

    rect r;
    //assign fields here
    r=r*5;
    

提交回复
热议问题