《新標准C++程序設計》4.7-4.9(C++學習筆記17)


一、重載類型強制轉換運算符

在C++中,類型的名字(包括類的名字)本身也是一種運算符,即類型強制轉換運算符。類型強制轉換運算符是單目運算符,也可以被重載,但只能重載為成員函數,不能重載為全局函數。經過適當重載后,“(類型名)對象”這個對對象進行類型強制轉換的表達式就等價於“對象.operator類型名()”,即變成對運算符函數的調用。

下面的程序對double類型類型強制轉換運算符進行了重載。

#include <iostream>
using namespace std;
class Complex
{
double real,imag;
public:
Complex(double r=0,double i=0):real(r),imag(i) { };
operator double () { return real; }
//重載強制類型轉換運算符 double
};
int main()
{
Complex c(1.2,3.4);
cout << (double)c << endl; //輸出 1.2
double n = 2 + c; //等價於 double n=2+c.operator double()
cout << n; //輸出 3.2
}

 

二、重載自增、自減運算符

自增運算符++、自減運算符--有前置/后置之分,為了區分所重載的是前 置運算符還是后置運算符,C++規定:

前置運算符作為一元運算符重載

重載為成員函數:

T & operator++();

T & operator--();

重載為全局函數:

T1 & operator++(T2);

T1 & operator--(T2);

后置運算符作為二元運算符重載,多寫一個沒用的參數:

重載為成員函數:

T operator++(int);

T operator--(int);

重載為全局函數:

T1 operator++(T2,int );

T1 operator—( T2,int);

但是在沒有后置運算符重載而有前置重載的情況下,在vs中,obj++ 也調用前置重載,而dev則令 obj ++ 編譯出錯

(1)

#include<iostream>
using namespace std;
int main()
{
  CDemo d(5);
  cout << (d++ ) << ","; //等價於 d.operator++(0);
  cout << d << ",";
  cout << (++d) << ","; //等價於 d.operator++();
  cout << d << endl;
  cout << (d-- ) << ","; //等價於 operator--(d,0);
  cout << d << ",";
  cout << (--d) << ","; //等價於 operator--(d);
  cout << d << endl;
  return 0;
}
class CDemo {
private :
  int n;
public:
  CDemo(int i=0):n(i) { }
  CDemo & operator++(); //用於前置形式
  CDemo operator++( int ); //用於后置形式
  operator int ( ) { return n; }
  friend CDemo & operator--(CDemo & );
  friend CDemo operator--(CDemo & ,int);
};
CDemo & CDemo::operator++()
{ //前置 ++
  ++n;
  return * this;
} // ++s即為: s.operator++();
CDemo CDemo::operator++( int k )
{ //后置 ++
  CDemo tmp(*this); //記錄修改前的對象
  n ++;
  return tmp; //返回修改前的對象
} // s++即為: s.operator++(0);
CDemo & operator--(CDemo & d)
{//前置--
  d.n--;
  return d;
} //--s即為: operator--(s);
CDemo operator--(CDemo & d,int)
{//后置--
  CDemo tmp(d);
  d.n --;
return tmp;
} //s--即為: operator--(s, 0);

(2)

operator int ( ) { return n; }

這里,int 作為一個類型強制轉換運算符被重載, 此后

Demo s;
(int) s ; //等效於 s.int();

類型強制轉換運算符被重載時不能寫返回值類型,實際上其返回值類型就是該類型強制轉換運算符代表的類型

 

三、運算符重載的注意事項

1. C++不允許定義新的運算符 ;

2. 重載后運算符的含義應該符合日常習慣 

complex_a + complex_b

word_a > word_b

date_b = date_a + n

3. 運算符重載不改變運算符的優先級;

4. 以下運算符不能被重載:“.”、“.*”、“::”、“?:”、sizeof;

5. 重載運算符()、[]、->或者賦值運算符=時,運算符重載函數必須聲明為類的成員函數。

 

Question:

如何區分自增運算符重載的前置形式和后置形式?

A) 重載時,前置形式的函數名是 ++ operator,后置形式的函數名是 operator ++

B) 后置形式比前置形式多一個 int 類型的參數

C) 無法區分,使用時不管前置形式還是后置形式,都調用相同的重載函數

D) 前置形式比后置形式多了一個int類型的參數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM