C++核心技術篇(六)

運算符的重載

算術運算符的重載
在前面的內容中曾介紹過string類型的數據,它是C++標準模板庫提供的一個類。string類支持使用加號“+”連接兩個string對象。但是使用兩個string對象相減卻是非法的,其中的原理是C++所提供類中重載運算符的功能。在string類中定義了運算符“+”和“+=”兩個符號的使用方法,這種方法的實質是一種成員函數。
關鍵字operator是專門實現類算符重載的關鍵字。在類成員中,定義一個這樣形式的函數:

返回值類型 operator 重載的運算符(參數列表)

一=以box類爲例,我們可以將加號“+”重載,之後獲得一個更大的盒子。
重載加號運算符
box.h的代碼如下:

class box{
public:
  //類成員變量
  float m_lenth;
  float m_width;
  float m_hight;
  int Number;
  //類成員函數
  box(float lenth,float width,float hight);
  box();
  box(const box& b);
  bool Compare(const box b) const;
  void ToCheck();
  void Rebuild (float lenth,float width,float hight);
  box operator+();
  };
  

在box,cpp中添加實現部分的代碼如下;

box::operator+(const box b) const{
   box box1(
   this->m_lenth+b.m_lenth;
   this->m_width+b.m_width;
   this->m_hight+b.m_hight;
   );
return box1;
}
box::box(const box& b){
this->Rebuild(b.m_lenth,b.m_width,b.m_hight);
cout<<"盒子的複製品創建"<<endl;
}

main.cpp程序入口的代碼如下:

#include"stdafx.h"
#include"box.h"
#include<iostream>
usng std::cout;
using std::endl;
using std::cin;
int main(){
const box boxA(3.2f,3.3f,3.4f);
const box boxB(4.1f,7.132f,6.094f);
box boxC=boxA+boxB;
boxC.ToCheck();

}

首先創建兩個box對象,使用box類定義的重載運算符加號將boxB作爲參數傳到函數中。這是產生複製對象,函數返回一個box對象,他的長寬高是boxA,boxB的和。boxC以這個返回值初始化,調用複製構造函數,最後輸出的是boxC的長、寬、高。

比較運算符的重載

除了加減乘除運算符外,比較運算符也可以被重載。根據比較運算符的運算規則,在重載時最好貼近他們的定義
重載比較運算符
box.h的代碼如下:

class box{
public :
//類成員變量
float m_lenth;
float m_width;
float m_hight;
int Number;
//類成員函數:
box(float lenth,float width,float hight);
box();
box(const box& b);
bool Compare(const box b) const;
void ToCheck();
void Bebuild(float lenth,float width,float hight);
box operator+();
bool operator>(const box b) const;
bool operator <(const box b) const;
};
在box.cpp中添加實現部分的代碼如下:

```java
bool box::operator>(const box b) const{
return (m_lenth>b.m_lenth)&(m_width>b.m_width)&(m_hight>b.m_hight);
}
bool box::operator<(const box b) const{
return (m_lenth<b.m_lenth)&(m_width<b.m_width)&(m_hight<b.m_hight);
}

程序入口main.cpp的代碼如下:

#include"stdafx.h"
#include"box.h"
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int main(){
box boxA(4.44f,3.33f,5.55f);
box boxB(14.44f,13.33f,15.55f);
box boxC(24.44f,3.33f,1.55f);
if(boxA>boxB){
cout<<"盒子A能夠完全容納盒子B"<<endl;
}
else if(boxA<boxB)
   cout<<"盒子B能夠完全容納下盒子A"<<endl;
else  
cout<<"這兩個盒子不能相互容納"endl;
if(boxC>boD){
cout<<"盒子C能夠完全容納盒子D"<<endl;
}
else if(boxA<boxB)
   cout<<"盒子D能夠完全容納下盒子C"<<endl;
else  
cout<<"這兩個盒子不能相互容納"endl;
return 0;
}

依據比較運算符的重載定義,程序共執行了4次比較。
除此之外,邏輯運算符、位運算符、賦值運算符(=,+=)調用運算符(即())等都可以被重載。
賦值運算符被重載會失去原來的定義,轉爲重載運算符函數。在重載算符時,最好貼近將算符應用於參數、成員變量等,使算符的意義與重載的意義相近。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章