zoukankan      html  css  js  c++  java
  • 关系运算符重载(==和!=)

    1.

    int strcmp(const char *s1, const char *s2);
    
    功能:比较 s1 和 s2 的大小,比较的是不相同的第一个字符ASCII码大小。
    
    参数:
    
    s1:字符串1首地址
    
    s2:字符串2首地址
    
    返回值:
    
    相等:0
    
    大于:>0
    
    小于:<0

    实例:

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Person
    {
    public:
        Person(string name, int age)
        {
            this->p_Name = name;
            this->p_Age = age;
        }
        //重载==关系运算符
        bool operator==(const Person& p)
        {
            if (this->p_Name == p.p_Name 
                && this->p_Age == p.p_Age)
            {
                return true;
            }
            return false;
        }
        //重载!=关系运算符
        bool operator!=(const Person& p)
        {
            if (this->p_Name != p.p_Name
                || this->p_Age != p.p_Age)
            {
                return true;
            }
            return false;
        }
    
        string p_Name;
        int p_Age;
    };
    
    void test01()
    {
        Person p1("小熊", 10);
        Person p2("小能", 10);
        Person p3("小能", 10);
        if (p1 == p2)
        {
            cout << "p1和p2相等" << endl;
        }
        else {
            cout << "p1和p2不等" << endl;
        }
        if (p3 == p2)
        {
            cout << "p3和p2相等" << endl;
        }
        else {
            cout << "p3和p2不等" << endl;
        }
        if (p1 != p3)
        {
            cout << "p1和p3不相等" << endl;
        }
        else {
            cout << "p1和p3相等" << endl;
        }
    }
    
    int main()
    {
        test01();
        system("Pause");
        return 0;
    }

    结果:

  • 相关阅读:
    WordCount
    vs2013安装及测试
    阅读程序,回答问题
    补作业:随机生成二元四则运算
    第一次合作
    漫漫“码农”路
    我的进度条
    Believe
    软件工程个人总结
    结队作业——电梯调度程序
  • 原文地址:https://www.cnblogs.com/yifengs/p/15175882.html
Copyright © 2011-2022 走看看