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 分钟前
C++类与对象(上)
开发语言·c++
mit6.82413 分钟前
[Nagios Core] struct监控对象 | 配置.cfg加载为内存模型
c语言·开发语言
泽020227 分钟前
C++之哈希表的基本介绍以及其自我实现(开放定址法版本)
c++
序属秋秋秋30 分钟前
《C++初阶之STL》【泛型编程 + STL简介】
开发语言·c++·笔记·学习
NCHUtianlin32 分钟前
JAVA生成PDF(itextpdf)
java·开发语言·pdf
点云SLAM2 小时前
二叉树算法详解和C++代码示例
数据结构·c++·算法·红黑树·二叉树算法
Sylvia-girl6 小时前
Java——抽象类
java·开发语言
Yana.nice8 小时前
Bash函数详解
开发语言·chrome·bash
m0_535064609 小时前
C++模版编程:类模版与继承
java·jvm·c++
tomorrow.hello10 小时前
Java并发测试工具
java·开发语言·测试工具