比较两个结构体是否相等

首先,是否可以使用memcmp来比较两个结构体是否相等呢?
  • 答案是不可以的。memcmp函数是逐个字节进行比较的,而struct存在字节对齐,字节对齐时补的字节内容是随机的,会产生垃圾值,所以无法比较。
结构体内存对齐的概念
  • 结构体变量中元素是按照定义顺序一个一个放到内存中去的,但并不是紧密排列的。从结构体存储的首地址开始,每一个元素放置到内存中时,它都会认为内存是以它自己的大小来划分的,因此元素放置的位置一定会在自己宽度的整数倍上开始。

那么,如何比较两个结构体是否相等呢?方法是:

使用: 重载操作符"=="
#include<iostream>
using namespace std;
struct A
{
	char ch;
	int val;
	//  友元运算符重载函数
	friend bool operator==(const A &ob1, const A &ob2);
	//  成员运算符重载函数
	bool operator==(const A &rhs);
};
bool operator==(const A  &ob1, const A &ob2)
{
	return (ob1.ch == ob2.ch && ob1.val == ob2.val);
}
bool A::operator==(const A &rhs)
{
	return (ch == rhs.ch && val == rhs.val);
}
int main()
{
	struct s s1, s2;
	s1.a = 1;
	s1.b = 2;
	s2.a = 1;
	s2.b = 2;
	if (s1 == s2)
		cout << "两个结构体相等" << endl;
	else
		cout << "两个结构体不相等" << endl;
	return 0;
}
//补充对齐的字节数中的内容是随机的
发布了80 篇原创文章 · 获赞 84 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43831728/article/details/105222786
今日推荐