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;
}
相关推荐
abcefg_h15 分钟前
MCP 实战指南:如何在项目中使用 Model Context Protocol 及其通信原理
开发语言·后端·golang·mcp
何以解忧,唯有..39 分钟前
Python 线程编程:从入门到实战
开发语言·python
_wxd6661 小时前
STL-stack与queue与priority_queue(容器适配器)
c++
zh路西法1 小时前
【玩转VLA具身智能机械臂】(二):MoveIt2 运动规划——架构、配置与 C++ 上手
c++·机械臂·路径规划·vla·planner·moveit2
SomeB1oody2 小时前
【RustyML入门】7.2. 深入模型持久化
开发语言·后端·机器学习·rust·教程
yaoxin5211232 小时前
502. Java 反射 - 编写 MessageInterceptor 类
java·开发语言
wuyk5552 小时前
Python零基础入门第五章:元组Tuple(不可变容器详解、列表与元组区别)
开发语言·python
三8442 小时前
PHP 污点分析绕过实战:CURL、get_meta_tags 与 fpm_get_status 引入非预定义污点源
开发语言·php
2601_965798472 小时前
Build a Fast, High-Ranking Restaurant Website with Rolanda Theme
开发语言·ios·swift