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;
}
相关推荐
沐知全栈开发1 天前
HTML5 浏览器支持
开发语言
wasp5201 天前
AgentScope Java 核心架构深度解析
java·开发语言·人工智能·架构·agentscope
WHOVENLY1 天前
【javaScript】- 笔试题合集(长期更新,建议收藏,目前已更新至31题)
开发语言·前端·javascript
慌糖1 天前
流-为序列化解释
开发语言
LXS_3571 天前
Day 18 C++提高 之 STL常用容器(string、vector、deque)
开发语言·c++·笔记·学习方法·改行学it
王琦03181 天前
Python 函数详解
开发语言·python
胡伯来了1 天前
13. Python打包工具- setuptools
开发语言·python
小鸡吃米…1 天前
Python 中的多层继承
开发语言·python
deng-c-f1 天前
Linux C/C++ 学习日记(53):原子操作(二):实现shared_ptr
开发语言·c++·学习
wanghowie1 天前
01.07 Java基础篇|函数式编程与语言新特性总览
java·开发语言·面试