# 運算符重載的規則
* 只能對C++已有的運算符進行重載,不能定義新的運算符
* 重載的運算符的作用的操作數至少有一個對象
* 不能改變運算符的運算對象的個數
* 不能改變運算符的優先級
* 不能改變運算符的結合性
* 重載運算符的函數不能有默認參數
* 當函數的參數列表中有兩個參數時,一般重載為友元形式
* 賦值運算符,下表運算符,函數調用運算符必須定義為函數的成員函數
* 流插入運算符,流提取運算符,類型轉換運算符不能定義為類的成員函數
# 定義方式
~~~
T operator 操作符(形參列表) ? ?//T代表返回值的類型
{
? ?··· ?//函數體
}
~~~
# 允許重載的運算符

# 不允許重載的運算符
| . | 成員訪問運算符 |
| --- | --- |
| .\* | 成員指針訪問運算符 |
| :: | 域運算符 |
| sizeof | 長度運算符 |
| ?: | 條件運算符 |
# 例子
~~~
#include <iostream>
using namespace std;
class String
{
? ?public:
String( ){p=NULL;} ? ? ? ? ? ? ? ? ? ? ? ? ? ? //默認構造函數
? String(char *str); ? ? ? ? ? ? ? ? ? ? ? ? ? ?//構造函數
? friend bool operator> (String &string1, String &string2);
? friend bool operator< (String &string1, String &string2);
? friend bool operator==(String &string1, String & string2);
? void display( );
? ?private:
? char *p; ? ? ? ? ? ? ? ? ? ? ? ? ? //字符型指針,用于指向字符串
};
?
String∷String(char *str) ? ? ? ? ? ? //定義構造函數
{
? ?p=str;
} ? ? ? ? ? ? ? ? ? ? ? ? ?//使p指向實參字符串
?
void String∷display( ) ? //輸出p所指向的字符串
{
? ?cout<<p;
}
bool operator>(String &string1,String &string2) ? ? ? ? ?//對運算符“>”重載
{
? ?if(strcmp(string1.p,string2.p)>0)
? ? ? ?return true;
? ?else
? ? ? ?return false;
}
bool operator<(String &string1,String &string2) ? ? ? ? ?//對運算符“<”重載
{
? ?if(strcmp(string1.p,string2.p)<0)
? ? ? ?return true;
? ?else
? ? ? ?return false;
}
bool operator==(String &string1,String&string2) //對運算符“==”重載
{
? ?if(strcmp(string1.p,string2.p)==0)
? ? ? ?return true;
? ?else
? ? ? ?return false;
}
void compare(String &string1,String &string2)
{
? ?if(operator>(string1,string2)==1)
? {
? ? ? ?string1.display( );
? ? ? ?cout<<″>″;
? ? ? ?string2.display( );
? }
? ?else
? ? ? ?if(operator<(string1,string2)==1)
? ? ? {
? ? ? ? ? ?string1.display( );cout<<″<″;string2.display( );
? ? ? }
? ?else if(operator==(string1,string2)==1)
? {
? ? ? ?string1.display( );cout<<″=″;string2.display( );
? }
? ?cout<<endl;
}
int main( )
{
? ?String string1(″Hello″),string2(″Book″),string3(″Computer″),string4(″Hello″);
? ?compare(string1,string2);
? ?compare(string2,string3);
? ?compare(string1,string4);
? ?return 0;
}
~~~
- 介紹
- 編程設計語言
- 第一章 對C++的初步認識
- 1.2 最簡單的C++程序
- 1.3 C++對C的補充
- 1.3.1 return
- 1.3.2 輸入輸出流
- 1.3.3 putchar 和 getchar
- 1.3.4 用const定義常變量
- 1.3.5 函數原型聲明
- 1.3.6 內置函數
- 1.3.7 函數重載
- 1.3.8 函數模板
- 1.3.9 有默認值的參數
- 1.3.10 作用域
- 1.3.11 const修飾指針
- 1.3.12 引用
- 1.3.13 生命期
- 1.3.14 變量
- 1.3.15 字符串變量
- 第二章 類與對象
- 2.2 類的聲明和對象的定義
- 2.3 類的成員函數
- 第三章 關于類和對象的進一步討論
- 3.1 構造函數
- 3.1.1 對象的初始化
- 3.1.2 構造函數
- 3.2 析構函數
- 3.3調用析構函數和構造函數的順序
- 3.4 對象數組
- 3.5 對象指針
- 3.6 共享數據的保護
- 3.7 對象的建立與釋放
- 3.8 對象的賦值與復制
- 3.9 靜態成員
- 3.10 友元
- 3.11 類模板
- 第四章 運算符重載
- 數據類型轉換
- 運算符重載
- 重載流插入運算符和流提取運算符
- 第五章 繼承與派生
- 繼承與派生
- 第六章 多態性與虛函數
- 多態性
- 虛函數
- 純虛函數與抽象類