系列文章目录
文章目录
一、判断两个结构体是否相等
- 系列文章目录
- 一、判断两个结构体是否相等
- 判断两个结构体是否相等:重载操作符"=="。
- 不能用函数memcpy来判断两个结构体是否相等:memcmp函数是逐个字节进行比较的,而struct存在字节对齐,字节对齐时补的字节内容是随机的,会产生垃圾值,所以无法比较。
#include
using namespace std;
struct s
{
int a;
int b;
bool operator == (const s &rhs);
};
bool s::operator == (const s &rhs)
{
return ((a == rhs.a) && (b == rhs.b));
}
int main()
{
struct s s1, s2;
s1.a = 1;
s1.b = 2;
s2.a = 1;
s2.b = 2;
if (s1 == s2)
cout
关注
打赏