#include<iostream>
using namespace std;
//重载关系运算符
class pers
{
public:
pers(string name, int age)
{
name = m_name;
age = m_age;
}
//重载==号
bool operator==(pers& p)
{
if (this->m_name == p.m_name && this->m_age == p.m_age)
{
return true;
}
return false;
}
bool operator!=(pers& p)
{
if (this->m_name == p.m_name || this->m_age == p.m_age)
{
return false;
}
return true;
}
string m_name;
int m_age;
};
void test897909()
{
pers p1("tom", 18);
pers p2("uihlj", 28);
if (p1 == p2)
{
cout << "p1和p2是相等的" << endl;
}
else
{
cout << "p1和p2是不相等的" << endl;
}
if (p1 != p3)
{
cout << "p1和p2是不相等的" << endl;
}
else
{
cout << "p1和p2是相等的" << endl;
}
}
int main()
{
test897909();
system("pause");
return 0;
}
p1与p2相等
跟着网课学的,一模一样的代码怎么搞都是p1和p2相等
怎么才能正常输出p1和p2不相等的结果
大哥 你是笔误把~
#include<iostream>
using namespace std;
//重载关系运算符
class pers
{
public:
pers(string name, int age)
{
name = m_name;
age = m_age;
}
//重载==号
bool operator==(pers& p)
{
if (this->m_name == p.m_name && this->m_age == p.m_age)
{
return true;
}
return false;
}
bool operator!=(pers& p)
{
if (this->m_name == p.m_name || this->m_age == p.m_age)
{
return false;
}
return true;
}
string m_name;
int m_age;
};
void test897909()
{
pers p1("tom", 18);
pers p2("uihlj", 28);
if (p1 == p2)
{
cout << "p1和p2是相等的" << endl;
}
else
{
cout << "p1和p2是不相等的" << endl;
}
}
int main()
{
test897909();
system("pause");
return 0;
}
效果: