我可以比较 C 中的 2 个结构吗?

新手上路,请多包涵

我只是简单地声明了一个这样的结构 -

 struct data{
    int x,y;
};

现在我已经声明了 --- 类型的 2 个变量 a & b data 类型。我已经为它们分配了适当的值。现在,我想检查它们是否相等!我正在尝试这样做-

 data a,b;
a.x=12, a.y=24;
b.x=15, b.y=30;
if(a!=b)cout<<"a~b"<<endl;

但是编译器在 4th 行上给了我以下错误->

error: no match for 'operator!=' (operand types are 'data' and 'data')

问题究竟出在哪里? C++ 不支持这种比较吗?还是我做错了什么??

执行此操作的确切和最简单的方法是什么?我需要分别比较结构中的每个元素吗?还是有其他更聪明的方法??

原文由 jbsu32 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 678
2 个回答

C++ 隐式地为您提供了逐个属性的赋值,但没有比较相等或排序。原因是“只是因为”,不要太看重哲学。

如果需要,您必须通过自己显式实现它们来提供这些运算符,例如:

 bool operator<(const Data& other) const {
    if (x < other.x) return true;
    if (x > other.x) return false;
    return y < other.y;
}

bool operator==(const Data& other) const {
    return x == other.x && y == other.y;
}

等等。

另请注意,例如定义 == 不会自动给您 != 并定义 < 不会提供 >= 隐含的 298966。78bddc70

更新

C++20 引入(将引入)一个新的运算符 <=> (友好名称“宇宙飞船运算符”)正是为了消除必须定义所有可能的关系运算符的冗长。在这种情况下添加:

 std::strong_ordering operator<=>(const Data& other) const {
    if (auto cmp = x <=> other.x; cmp != 0) return cmp;
    return y <=> other.y;
}

will allow compilation of all relational tests ( < , <= , > , >= , == , != ) 类的元素之间基于检查 x 首先,如果该检查没有解决,检查 y 代替。

原文由 6502 发布,翻译遵循 CC BY-SA 4.0 许可协议

您必须实施 bool operator != (const data&, const data&);

可能的实现(在 c++11 中):

 #include <tuple>

//...

bool operator == (const data& lhs, const data& rhs) {
    return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y);
}

bool operator != (const data& lhs, const data& rhs) {
    return !(lhs == rhs);
}

原文由 Jarod42 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏