//重载== ==出现在判断语句中
bool operator==(Person &ob)
{
if(strcmp(this->name, ob.name) == 0)
{
return true;
}
return false;
}
//重载!= !=出现在判断语句中
bool operator!=(Person &ob)
{
if(strcmp(this->name, ob.name) != 0)
{
return true;
}
return false;
}
void test02()
{
Person ob1("lucy");
Person ob2("lucy");
Person ob3("bob");
if(ob1 == ob2)
{
cout<<"ob1 == ob2"<<endl;
}
else
{
cout<<"ob1 != ob2"<<endl;
}
if(ob1 != ob3)
{
cout<<"ob1 != ob3"<<endl;
}
else
{
cout<<"ob1 == ob3"<<endl;
}
}
运行结果

本文通过一个具体的C++代码示例,展示了如何为Person类重载==和!=操作符,用以比较两个对象的name属性是否相同。通过在test02函数中使用这些重载的操作符,验证了其正确性和有效性。
511

被折叠的 条评论
为什么被折叠?



