编辑整个数据结构c ++?

时间:2017-11-07 21:50:27

标签: c++ data-structures

我对数据结构有疑问。有没有办法一次编辑整个结构,而不是一次编辑一个变量? FI:

struct foo
{
  int a=5;
  int b=4;
  int c=8;
};
int main()
{
    foo f;

    f-1;

    return 0;

}

结果:

  f.int a=4;
  f.int b=3;
  f.int c=7;

如果有办法做到这一点,那么在我制作的特定项目中,这将有很大帮助。无论如何,谢谢你的时间和帮助" D

2 个答案:

答案 0 :(得分:7)

您可能正在寻找operator overloading

struct foo
{
  int a=5;
  int b=4;
  int c=8;
  foo operator-(int val) const {
      foo copy(*this);
      copy.a -= val;
      copy.b -= val;
      copy.c -= val;
      return copy;
  }
};
int main()
{
    foo f;

    f = f - 1;

    return 0;

}

如果您在编译时不知道参数的数量,也可以查看valarray

答案 1 :(得分:1)

answer by Xirema已经回答了您的问题。

我只想指出,如果你支持f-1作为运算符函数,你应该也支持几个运算符。

幸运的是,您可以重复使用某些实现来实现其他实现。

这是我的建议:

struct foo
{
   int a=5;
   int b=4;
   int c=8;

   // Pre-increment
   foo& operator++()
   {
      ++a;
      ++b;
      ++c;
      return *this;
   }

   // Post-increment
   foo operator++(int)
   {
      foo copy = *this;
      ++(*this);
      return copy;
   }

   // Pre-decrement
   foo& operator--()
   {
      --a;
      --b;
      --c;
      return *this;
   }

   // Post-decrement
   foo operator--(int)
   {
      foo copy = *this;
      --(*this);
      return copy;
   }

   // Increment
   foo& operator+=(int v)
   {
      a += v;
      b += v;
      c += v;
      return *this;
   }

   // Decrement
   foo& operator-=(int v)
   {
      // Use the inrement operator.
      return ( (*this) += (-v));
   }

   // Addition
   foo operator+(int v) const
   {
      foo copy = *this;
      copy += v;
      return copy;
   }

   // Subtraction
   foo operator-(int v) const
   {
      // Use the addition operator.
      return ((*this) + (-v));
   }
};

测试代码:

int main()
{
   foo f1;

   // Pre-increment
   ++f1;

   // Post-increment
   f1++;

   // Pre-decrement
   --f1;

   // Post-decrement
   f1--;

   // Increment
   f1 += 10;

   // Decrement
   f1 -= 20;

   // Addition
   foo f2 = f1 + 20;

   // Subtraction
   foo f3 = f2 - 50;
}
相关问题