首页 > 编程语言 > 详细

C++重载<运算符

时间:2021-02-24 23:32:22      阅读:31      评论:0      收藏:0      [点我收藏+]

C++的string已经定义了各种比较运算符。

C风格的字符串(char数组)则采用strcmp比较字符串大小。详细见下

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;

// 先按成绩比较
// 成绩相同按名字,
// 名字相同按年龄 
struct Student {
    char name[101];
    int age;
    int score;
    // ①const Student& 既可以持有常量也可以持有变量,持有变量时不改变。 
    // ②Class::fun() const 表示该函数不修改类对象,也就是不修改成员变量,如果改了,编译器报错。 
    bool operator < (const Student& b) const {
        if (score != b.score) return score < b.score;
        int tmp = strcmp(name, b.name);
        // ③strcmp 自左向右直到出现不同的字符或者‘\0‘ 
        // 按ASCII值大小相比较,若s1=s2则返回0,s1<s2返回负数,s1>s2返回正数。 
        if (tmp != 0) return tmp < 0;
        else return age < b.age;
    }        
};

int main()
{
    Student x = {"aaa", 18, 99};
    Student y = {"bbb", 18, 99};
    
    printf("%s\n", x < y ? "yes" : "no");
    
    return 0;
}

 

C++重载<运算符

原文:https://www.cnblogs.com/xkxf/p/14442233.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!