判断两个结构体是否相等+是否能用memcmp函数判断结构体相等

判断两个结构体是否相等:重载操作符"=="

#include<iostream>

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 << "两个结构体相等" << endl;
	else
		cout << "两个结构体不相等" << endl;
	return 0;
}

不能用函数memcpy来判断两个结构体是否相等:memcmp函数是逐个字节进行比较的,而struct存在字节对齐,字节对齐时补的字节内容是随机的,所以无法比较。


猜你喜欢

转载自blog.csdn.net/lizhentao0707/article/details/80888501