国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

詳解C++編程中一元運算符的重載

2020-05-23 14:09:54
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了C++編程中一元運算符的重載,特別對遞增和遞減運算符重載作了著重講解,需要的朋友可以參考下
 

可重載的一元運算符如下:

  1. !(邏輯“非”)
  2. &(取址)
  3. ~(二進制反碼)
  4. *(取消指針引用)
  5. +(一元加)
  6. -(一元求反)
  7. ++(遞增)
  8. --(遞減)
  9. 轉換運算符

后綴遞增和遞減運算符(++ 和 ––)在遞增和遞減中單獨處理,下面會講到。

以下規則適用于所有其他一元運算符。若要將一元運算符函數聲明為非靜態成員,則必須用以下形式聲明它:
ret-type operator op ()
其中 ret-type 是返回類型,op 是上表中列出的運算符之一。
若要將一元運算符函數聲明為全局函數,則必須用以下形式聲明它:
ret-type operator op (arg )
其中 ret-type 和 op 如上所述用于成員運算符函數,arg 是要參與運算的類類型的參數。
注意
一元運算符的返回類型沒有限制。例如,邏輯“非”(!) 返回整數值是合理的,但并非強制性的。

遞增和遞減運算符重載
由于遞增和遞減運算符各有兩個變量,因此它們屬于一個特殊類別:

  • 前置遞增和后置遞增
  • 前置遞減和后置遞減

編寫重載的運算符函數時,為這些運算符的前綴和后綴版本實現單獨的版本很有用。若要區分這兩者,請遵循以下規則:運算符的前綴形式與聲明任何其他一元運算符的方式完全相同;后綴形式接受 int 類型的其他參數。

注意
當為遞增或遞減運算符的前綴形式指定重載運算符時,其他參數的類型必須是 int;指定任何其他類型都將產生錯誤。
以下示例顯示如何為 Point 類定義前綴和后綴遞增和遞減運算符:

// increment_and_decrement1.cppclass Point{public:  // Declare prefix and postfix increment operators.  Point& operator++();    // Prefix increment operator.  Point operator++(int);   // Postfix increment operator.  // Declare prefix and postfix decrement operators.  Point& operator--();    // Prefix decrement operator.  Point operator--(int);   // Postfix decrement operator.  // Define default constructor.  Point() { _x = _y = 0; }  // Define accessor functions.  int x() { return _x; }  int y() { return _y; }private:  int _x, _y;};// Define prefix increment operator.Point& Point::operator++(){  _x++;  _y++;  return *this;}// Define postfix increment operator.Point Point::operator++(int){  Point temp = *this;  ++*this;  return temp;}// Define prefix decrement operator.Point& Point::operator--(){  _x--;  _y--;  return *this;}// Define postfix decrement operator.Point Point::operator--(int){  Point temp = *this;  --*this;  return temp;}int main(){}

可使用以下函數頭在文件范圍中(全局)定義同一運算符:

friend Point& operator++( Point& )   // Prefix incrementfriend Point& operator++( Point&, int ) // Postfix incrementfriend Point& operator--( Point& )   // Prefix decrementfriend Point& operator--( Point&, int ) // Postfix decrement

表示遞增或遞減運算符的后綴形式的 int 類型的參數不常用于傳遞參數。它通常包含值 0。但是,可按以下方式使用它:

// increment_and_decrement2.cppclass Int{public:  Int &operator++( int n );private:  int _i;};Int& Int::operator++( int n ){  if( n != 0 )  // Handle case where an argument is passed.    _i += n;  else    _i++;    // Handle case where no argument is passed.  return *this;}int main(){  Int i;  i.operator++( 25 ); // Increment by 25.}

除顯式調用之外,沒有針對使用遞增或遞減運算符來傳遞這些值的語法,如前面的代碼所示。實現此功能的更直接的方法是重載加法/賦值運算符 (+=)。



發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 内江市| 宜兴市| 铜陵市| 洛阳市| 临潭县| 龙门县| 威海市| 崇阳县| 忻州市| 东光县| 溧水县| 黄梅县| 勐海县| 都兰县| 巴楚县| 霸州市| 镇巴县| 枣阳市| 莱芜市| 玛曲县| 天门市| 泸定县| 松阳县| 辽阳县| 临清市| 筠连县| 和林格尔县| 云龙县| 扶余县| 霍林郭勒市| 昌吉市| 邯郸市| 迁安市| 勃利县| 临清市| 称多县| 深州市| 林甸县| 宁津县| 上高县| 石阡县|