c++中關(guān)系運(yùn)算符重載的實(shí)現(xiàn)示例
在 C++ 中,關(guān)系運(yùn)算符重載 允許我們?yōu)樽远x類型(如類、結(jié)構(gòu)體)定義關(guān)系運(yùn)算(如 、!=、<、>、<=、>=)的行為,使自定義類型能像內(nèi)置類型(int、float 等)一樣使用關(guān)系運(yùn)算符。
一、關(guān)系運(yùn)算符的基本規(guī)則
1、可重載的關(guān)系運(yùn)算符:、!=、<、>、<=、>=。
2、重載方式:
成員函數(shù)(推薦,尤其是</>,符合封裝性);
全局函數(shù)(需訪問私有成員時(shí),可聲明為友元)。
3、返回值:通常返回 bool 類型(表示運(yùn)算結(jié)果的真假)。
4、對(duì)稱性:!= 可基于 == 實(shí)現(xiàn),>= 可基于 < 實(shí)現(xiàn),避免重復(fù)代碼。
5、const 修飾:若重載為成員函數(shù),建議加 const(保證對(duì)常量對(duì)象也能調(diào)用)。
二、核心示例:自定義類的關(guān)系運(yùn)算符重載
以 Person 類為例,重載 ==、!=、<(按年齡比較):
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
// 構(gòu)造函數(shù)
Person(string n, int a) : name(n), age(a) {}
// ========== 1. 重載 == (成員函數(shù) + const) ==========
bool operator==(const Person& other) const {
// 自定義比較規(guī)則:姓名和年齡都相同則相等
return (this->name == other.name) && (this->age == other.age);
}
// ========== 2. 重載 != (基于 == 實(shí)現(xiàn)) ==========
bool operator!=(const Person& other) const {
return !(*this == other); // 復(fù)用 ==,避免重復(fù)邏輯
}
// ========== 3. 重載 < (按年齡比較) ==========
bool operator<(const Person& other) const {
return this->age < other.age;
}
// ========== 4. 重載 > (基于 < 實(shí)現(xiàn)) ==========
bool operator>(const Person& other) const {
return other < *this; // 復(fù)用 <,簡(jiǎn)化邏輯
}
// 輔助函數(shù):打印信息
void show() const {
cout << "姓名:" << name << ",年齡:" << age << endl;
}
};
int main() {
Person p1("張三", 20);
Person p2("李四", 25);
Person p3("張三", 20);
// 測(cè)試 ==
if (p1 == p3) {
cout << "p1 和 p3 相等" << endl;
} else {
cout << "p1 和 p3 不相等" << endl;
}
// 測(cè)試 !=
if (p1 != p2) {
cout << "p1 和 p2 不相等" << endl;
}
// 測(cè)試 <
if (p1 < p2) {
cout << "p1 年齡小于 p2" << endl;
}
// 測(cè)試 >
if (p2 > p1) {
cout << "p2 年齡大于 p1" << endl;
}
return 0;
}
三、全局函數(shù)重載(友元版)
若需通過(guò)全局函數(shù)重載(例如需要對(duì)稱處理左操作數(shù)為內(nèi)置類型的情況),可將函數(shù)聲明為類的友元:
class Person {
private:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
// 聲明友元函數(shù)(重載 ==)
friend bool operator==(const Person& p1, const Person& p2);
// 聲明友元函數(shù)(重載 !=)
friend bool operator!=(const Person& p1, const Person& p2);
};
// 實(shí)現(xiàn)友元函數(shù)(==)
bool operator==(const Person& p1, const Person& p2) {
return p1.name == p2.name && p1.age == p2.age;
}
// 實(shí)現(xiàn)友元函數(shù)(!=)
bool operator!=(const Person& p1, const Person& p2) {
return !(p1 == p2);
}
四、關(guān)鍵注意事項(xiàng)
1、避免冗余:
!= 基于 == 實(shí)現(xiàn),>= 基于 < 實(shí)現(xiàn),<= 基于 > 實(shí)現(xiàn),減少代碼重復(fù)。
示例:bool operator>=(const Person& other) const { return !(*this < other); }
2、const 正確性:
成員函數(shù)重載時(shí),必須加 const(保證常量對(duì)象可調(diào)用)。
函數(shù)參數(shù)也建議加 const(避免修改實(shí)參)。
3、對(duì)稱性:
若重載為全局函數(shù),左 / 右操作數(shù)類型對(duì)稱(如 operator==(int, Person) 和 operator==(Person, int))。
成員函數(shù)重載時(shí),左操作數(shù)固定為類對(duì)象(如 p1 < p2 等價(jià)于 p1.operator<(p2))。
4、不要改變運(yùn)算符語(yǔ)義:
重載的關(guān)系運(yùn)算符應(yīng)符合直覺(如 == 表示 “相等”,而非其他邏輯)。
5、編譯器默認(rèn)行為:
C++ 不會(huì)為自定義類默認(rèn)生成 ==、< 等關(guān)系運(yùn)算符(需手動(dòng)重載)。
但會(huì)默認(rèn)生成拷貝賦值運(yùn)算符(=),需注意區(qū)分。
五、常見場(chǎng)景
自定義數(shù)據(jù)結(jié)構(gòu)(如鏈表、樹)的元素比較;
排序算法(如 std::sort)中,自定義類對(duì)象的排序規(guī)則(需重載 <);
容器查找(如 std::find)中,判斷元素是否相等(需重載 ==)。
例如,使用 std::sort 排序 Person 數(shù)組(需重載 <):
#include <algorithm>
#include <vector>
int main() {
vector<Person> vec = {Person("張三", 25), Person("李四", 20), Person("王五", 30)};
sort(vec.begin(), vec.end()); // 依賴 operator< 重載(按年齡排序)
for (const auto& p : vec) {
p.show(); // 輸出:李四(20)、張三(25)、王五(30)
}
return 0;
}
通過(guò)合理重載關(guān)系運(yùn)算符,可讓自定義類型的使用更接近內(nèi)置類型,提升代碼可讀性和易用性。
到此這篇關(guān)于c++中關(guān)系運(yùn)算符重載的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)c++ 關(guān)系運(yùn)算符重載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
簡(jiǎn)要對(duì)比C語(yǔ)言中三個(gè)用于退出進(jìn)程的函數(shù)
這篇文章主要介紹了C語(yǔ)言中三個(gè)用于退出進(jìn)程的函數(shù)的對(duì)比,分別為_exit()函數(shù)和on_exit()函數(shù)以及atexit()函數(shù),需要的朋友可以參考下2015-08-08
C++中fstream,ifstream及ofstream用法淺析
這篇文章主要介紹了C++中fstream,ifstream及ofstream用法,適合C++初學(xué)者學(xué)習(xí)文件流的操作,需要的朋友可以參考下2014-08-08
淺談C++/C關(guān)于#define的那些奇奇怪怪的用法
本文主要介紹了C++/C關(guān)于#define的那些奇奇怪怪的用法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
C語(yǔ)言版學(xué)生成績(jī)管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言版學(xué)生成績(jī)管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
Qt各種字符轉(zhuǎn)換的實(shí)現(xiàn)示例
本文主要介紹了Qt各種字符轉(zhuǎn)換的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05
Qt?http編程之nlohmann?json庫(kù)使用詳解
nlohmann是一個(gè)C++的JSON庫(kù),它提供了方便的方式來(lái)解析、生成和操作JSON數(shù)據(jù),這篇文章主要為大家介紹了nlohmann?json庫(kù)的簡(jiǎn)單使用,希望對(duì)大家有所幫助2024-04-04

