C++ 46 之 关系运算符的重载

cpp 复制代码
#include <iostream>
#include <string>
using namespace std;

class Students06{
public:
    string m_name;
    int m_age;
    Students06(string name, int age){
        this->m_name = name;
        this->m_age = age;
    }

    // 重载了 ==
    bool operator==(Students06 &stu){
        if(this->m_name == stu.m_name && this->m_age == stu.m_age){
            return true;
        }
        else{
            return false;
        }
    }

    // 重载了 !=
    // this->m_name == stu.m_name && this->m_age == stu.m_age 词语会自动返回 true 或 false
    bool operator!=(Students06 &stu){
        return !(this->m_name == stu.m_name && this->m_age == stu.m_age);
    }    
};


int main()
{
    // int a = 10;
    // int b = 20;
    // if(a==b)
    // {
    //     cout << "a==b" << endl;
    // }    
    // else{
    //     cout<< "a != b" << endl;
    // }


    Students06 stu1("四",18);
    Students06 stu2("五",18);
    // if(stu1 == stu2){
    //     cout << "stu1 == stu2"<< endl;
    // }
    // else{
    //     cout << "stu1 != stu2"<< endl;
    // }

    if(stu1 != stu2){
        cout << "stu1!=stu2"<< endl;
    }
    else{
        cout<< "stu1 == stu2" << endl;
    }

    return 0;
}
相关推荐
крон2 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan3 小时前
c++ 单例模式
开发语言·c++·单例模式
老胖闲聊3 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1184 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之4 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?4 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头5 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
liuyang-neu5 小时前
java内存模型JMM
java·开发语言
利刃大大5 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
喜欢吃燃面5 小时前
C++刷题:日期模拟(1)
c++·学习·算法