编辑整个数据结构 c++
Editing an entire data structure c++?
我有一个关于数据结构的问题。有没有办法一次编辑整个结构,而不是一次编辑一个变量?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
您可能正在寻找运算符重载。
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
。
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;
}
相关文章:
- 链表,反向函数,数据结构
- 如何使用set实现无序数据结构?
- 我们可以将数据永久保存为数据结构吗?
- C++中的可变长度数组/数据结构
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 通过 NIF 从C++返回自定义数据结构
- 编译器上的策略数据结构不起作用
- 尝试构建"lock-free"数据结构C++
- 设计将引用元素移动到开头的数据结构.C++
- 在学习数据结构之前对STL有一个了解是好的吗?
- 如何解析表示树状数据结构的字符串
- 我对数据结构、双向链表有一些问题
- googletest:测试太大的数据结构
- C++中deque数据结构的大O是什么?
- 我可以使用哪种数据结构来处理这种方式
- 将文本文件解析为树状数据结构
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- 哪些存储了不完整类型的 STL 数据结构可以用作类成员?
- C++,您能否设计一种数据结构,将指针保存在连续内存中并且不会使它们失效?
- 带参数的数据结构的全局声明