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;
}
相关推荐
小叶学C++9 分钟前
【C++】类与对象(下)
java·开发语言·c++
ac-er888810 分钟前
PHP“===”的意义
开发语言·php
NuyoahC26 分钟前
算法笔记(十一)——优先级队列(堆)
c++·笔记·算法·优先级队列
jk_10129 分钟前
MATLAB中decomposition函数用法
开发语言·算法·matlab
weixin_4640780729 分钟前
C#串口温度读取
开发语言·c#
无敌の星仔31 分钟前
一个月学会Java 第2天 认识类与对象
java·开发语言
豆豆1 小时前
为什么用PageAdmin CMS建设网站?
服务器·开发语言·前端·php·软件构建
FL16238631291 小时前
[C++]使用纯opencv部署yolov11-pose姿态估计onnx模型
c++·opencv·yolo
sukalot1 小时前
windows C++-使用任务和 XML HTTP 请求进行连接(一)
c++·windows
落落落sss1 小时前
MybatisPlus
android·java·开发语言·spring·tomcat·rabbitmq·mybatis