Advertisement

C++基础知识 - 重载关系运算符>、<、==

阅读量:

重载关系运算符>、<、==

C++ 提供了多种关系运算符(如 < 和 > 等),这些运算符常用于比较 C++ 内置的数据类型,并返回一个bool类型的值。

允许我们对任意一个关系运算符进行重载,并且这些被重载后的运算符会被用来处理比较类的对象

这一实例具体说明了如何实现<运算符的重载,在这种模式下,我们还可以尝试实现其他关系运算符的重载

Boy.h

复制代码
    #pragma once
    #include <string>
    using namespace std;
    
    class Boy{
    public:
    	Boy(const char* name = "无名", int age = 0, int salary = 0);
    	~Boy();
    
    	//定义了<运算符重载, 返回值为bool类型
    	bool operator<(const Boy& boy);
    	
    	string description() const;
    private: 
    	char* name;	//姓名
    	int age;	//年龄
    	int salary;	//薪资
    };

Boy.cpp

复制代码
    #include <iostream>
    #include <sstream>
    #include "Boy.h"
    
    Boy::Boy(const char* name, int age, int salary){
    if (!name) {
        name = (char*)"未命名";
    }
    this->name = new char[strlen(name)+1];
    strcpy_s(this->name, strlen(name)+1, name);
    this->age = age;
    this->salary = salary;
    }
    
    Boy::~Boy(){
    if (name) {
        delete name;
        name = NULL;
    }
    }
    
    //比较规则,如果当前对象的薪资小于boy对象的薪资
    bool Boy::operator<(const Boy& boy){
    if (this->salary < boy.salary) {
        return true; 
    } else {
        return false;
    }
    }
    
    string Boy::description() const{
    stringstream ret;
    ret << "姓名:" << name << "\t年龄:" << age << "\t薪资:" << salary;
    return ret.str();
    }

main.cpp

复制代码
    #include <iostream>
    #include <Windows.h>
    #include "Boy.h"
    using namespace std;
    
    int main(void) {
    	Boy boy1("张三", 18, 10000);
    	Boy boy2("李四", 19, 15000);
    
    	//调用 bool operator<(const Boy& boy);
    	if (boy1 < boy2) {
    		cout << "薪资最高的是:" << boy2.description() << endl;
    	} else {
    		cout << "薪资最高的是:" << boy1.description() << endl;
    	}
    
    	system("pause");
    	return 0;
    }

全部评论 (0)

还没有任何评论哟~