第四周 運算符重載
1.運算符重載的基本概念
2.賦值運算符的重載
3.運算符重載爲友元函數
4.運算符重載實例:可變長數組類的實現
5.流插入運算符和流提取運算符的重載
6.類型轉換運算符、自增自減運算符的重載
5.流插入運算符和流提取運算符的重載
cout << 5 << “this”;爲什麼能夠成立?
cout是什麼?“<<” 爲什麼能用在 cout上?
流插入運算符的重載
cout 是在 iostream 中定義的,ostream 類的對象。
“<<” 能用在cout 上是因爲,在iostream裏對 “<<” 進行了重載。
考慮,怎麼重載才能使得cout << 5; 和 cout << “this”都能成立?
有可能按以下方式重載成 ostream類的成員函數,返回值是void:
void ostream::operator<<(int n)
{
…… // 輸出n 的代碼
return;
}
void ostream::operator<<(const char * s)
{
…… // 輸出n 的代碼
return;
}
cout << 5 ; 即 cout.operator<<(5);
cout << “this”; 即 cout.operator<<( “this” );
怎麼重載才能使得cout << 5 << “this” ;成立?注意返回值。
ostream & ostream::operator<<(int n)
{
…… // 輸出n 的代碼
return * this;
}
ostream & ostream::operator<<(const char * s )
{
…… // 輸出s 的代碼
return * this;
}
cout << 5 << “this”;本質上的函數調用的形式是:cout.operator<<(5).operator<<(“this”);
流插入運算符的重載
假定下面程序輸出爲 5hello, 該補寫些什麼?
class CStudent{
public:
int nAge;
};
int main(){
CStudent s ;
s.nAge = 5;
cout << s <<"hello";
return 0;
}
將<<重載爲全局的函數。
ostream & operator<<( ostream & o,const CStudent & s){
o << s.nAge ;
return o;
}
例子:假定c是Complex複數類的對象,現在希望寫“cout << c;”,就能以“a+bi”的形式輸出c的值,寫“cin>>c;”,就能從鍵盤接受“a+bi”形式的輸入,並且使得c.real = a,c.imag = b。
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Complex {
double real,imag;
public:
Complex( double r=0, double i=0):real(r),imag(i){ };
friend ostream & operator<<( ostream & os,
const Complex & c);
friend istream & operator>>( istream & is,Complex & c);
};
ostream & operator<<( ostream & os,const Complex & c)
{
os << c.real << "+" << c.imag << "i"; // 以"a+bi" 的形式輸出
return os;
}
istream & operator>>( istream & is,Complex & c)
{
string s;
is >> s; // 將"a+bi" 作爲字符串讀入, “a+bi” 中間不能有空格
int pos = s.find("+",0);
string sTmp = s.substr(0,pos); // 分離出代表實部的字符串
c.real = atof(sTmp.c_str()); //atof 庫函數能將const char* 指針指向的內容轉換成 float
sTmp = s.substr(pos+1, s.length()-pos-2); // 分離出代表虛部的字符串
c.imag = atof(sTmp.c_str());
return is;
}
int main() {
Complex c;
int n;
cin >> c >> n;
cout << c << "," << n;
return 0;
}
程序運行結果可以如下:
13.2+133i 87 ↙
13.2+133i, 87