首页 > 其他分享 >关于重载==运算符的问题

关于重载==运算符的问题

时间:2023-01-20 18:55:53浏览次数:31  
标签:10 cout Age push back 运算符 Person 关于 重载

提问:

 如下代码所示,不理解我定义的Person类里的==重载函数为什么这么写? bool operator==(const Person &p)中的this->m_Age和o.m_Age搞糊涂了

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
 
//自定义数据类型
class Person
{
public:
    Person(string name, int age)
    {
        this->m_Name = name;
        this->m_Age = age;
    }
                //不理解下面这个重载函数,希望各位大佬帮我看看
    bool operator==(const Person &p)
    {
        //cout << "p.m_Age:" << p.m_Age << "\t this->m_Age:" << this->m_Age << endl;
        if (p.m_Age == this->m_Age)
        {
            return true;
        }
 
        else
        {
            return false;
        }
    }
 
    string m_Name;
    int m_Age;
};
 
class myPrint2
{
public:
 
    void operator()(const Person & p)
    {
        cout << "姓名:" << p.m_Name << "\t年龄:" << p.m_Age << endl;
    }
};
 
void test02()
{
    Person p1("aa", 10);
    Person p2("bb", 30);
    Person p3("cc", 20);
    Person p4("dd", 10);
    Person p5("ee", 40);
    Person p6("ff", 10);
    vector<Person>v;
    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);
    v.push_back(p4);
    v.push_back(p5);
    v.push_back(p6);
    //将所有10替换为1000
    Person pOld("aa", 10);
    Person pNew("aa", 1000);
    cout << "替换前:" << endl;
    for_each(v.begin(), v.end(), myPrint2());
    cout << "\n替换后:" << endl;
    replace(v.begin(), v.end(), pOld, pNew);
    
    for_each(v.begin(), v.end(), myPrint2());
}
 
int main()
{
    //test01();
    test02();
 
    system("pause");
    return 0;
}
 

解答:

 对着呢呀,比较两个人是否相等的时候,就是比较他们的年龄。p是传进来的对象,this是当前对象。

标签:10,cout,Age,push,back,运算符,Person,关于,重载
From: https://www.cnblogs.com/dituirenwu/p/17063018.html

相关文章