運(yùn)算符重載:與function overloading異曲同工的是,C++提供所謂的Operator overloading。所謂operators是像??+(加)-(減)*(乘)/(除)>>(位右移)
<<(位左移)之類(lèi)的符號(hào),代表一種動(dòng)作。
面對(duì)operators,我們應(yīng)該把他想像是一種函數(shù),只不過(guò)形式比較特殊罷了。一般函數(shù)的參數(shù)出現(xiàn)在括號(hào)()之中,而operator的參數(shù)圍繞著一個(gè)operator符號(hào)(之前或之后),編程語(yǔ)言?xún)?nèi)置的數(shù)據(jù)類(lèi)型(比如整數(shù)`int`、浮點(diǎn)數(shù)`float`、長(zhǎng)整數(shù)`long`等)所使用的操作符(比如加法`+`、減法`-`、乘法`*`等)是由語(yǔ)言本身直接提供的,而不是通過(guò)任何外部庫(kù)或模塊來(lái)實(shí)現(xiàn)的。
C++允許程序員為class type's object設(shè)計(jì)專(zhuān)門(mén)的operators,使objects的操作能夠像內(nèi)建型別的一樣的自然而直觀(guān)。讓operator以種形式呈現(xiàn),但符號(hào)不變,這個(gè)就是operator overloading。
Operator overloading的存在一下褒貶不一,支持者認(rèn)為它使得程序代碼變得更精簡(jiǎn)漂亮,反對(duì)者認(rèn)為容易把程序員搞迷糊掉。但是,我想,誰(shuí)都不可否認(rèn)下面這樣的程序代碼確實(shí)是精簡(jiǎn)漂亮:
CString str1("Hello, I am J.J.Hou, "); CString str2("How are you?"); CString str3 = str1 + str2; // + 是 CString的一個(gè)overloaded operator // 于是 str3 為 "Hello, I am J.J.Hou, How are you?" int i = 5; double pi = 3.141592653; cout << "i=" << i << " and pi=" << pi << endl; // 于是 console 屏幕上出現(xiàn)"i=5 and pi=3.141592653"。
現(xiàn)在讓我示范一個(gè)overloaded operator的作法,只要在以下類(lèi)的代碼中加入第18~21行的+號(hào)的重載代碼,即可完成CPoint的加法運(yùn)算:
1 class CPoint{ 2 3 public: 4 5 CPoint() 6 { 7 _x=0; 8 9 } 10 11 CPoint(float y){ 12 13 _x=y; 14 } 15 float x(){return _x;} 16 void x(float xval){_x=xval;} 17 18 CPoint operator+(const CPoint& pt) const //對(duì)+號(hào)進(jìn)行重載 19 { 20 return CPoint(_x+pt._x); 21 } 22 23 protected: 24 float _x; 25 26 };
以operator開(kāi)頭的函數(shù),表示是個(gè)運(yùn)算子。加法運(yùn)算子需要左右兩個(gè)運(yùn)算元(operands),左側(cè)運(yùn)算元即成為本函數(shù)的this指向的對(duì)象,右側(cè)運(yùn)算元?jiǎng)t是本函數(shù)的參數(shù)pt。上述函數(shù)代碼如果像下面這樣表示,會(huì)比較清晰,但兩者其實(shí)是相同的(因?yàn)閠his指針是個(gè)隱藏參數(shù)):
CPoint operator+(const CPoint& pt) const //對(duì)+號(hào)進(jìn)行重載 { return CPoint(this->_x+pt._x); }
有了上述的 CPoint::operator+,現(xiàn)在你可以這么使用它:
1 CPoint pt1(7.2), pt2(5.3), pt3; 2 pt3 = pt1 + pt2; 3 cout << "pt3.x = " << pt3.x() << endl; // 12.5
C++中,<<和>>是最常用的重載運(yùn)算符,用于表示對(duì)標(biāo)準(zhǔn)輸入輸出設(shè)備(如屏幕和鍵盤(pán))的讀寫(xiě)操作,極大地方便了編程,可替代繁瑣的printf()和scanf()函數(shù)。這兩個(gè)運(yùn)算符在iostream庫(kù)中定義,為C++編程提供了極大的便利。
Insertion Operator( <<) for stdout: <<本來(lái)是位左移運(yùn)算符,但是在C++的標(biāo)準(zhǔn)庫(kù)iostream中被改頭換面,其左側(cè)的運(yùn)算元(operand)被指定為cout(console output device),右側(cè)運(yùn)算元是一個(gè)內(nèi)建型別的objects。我們可以利用它很方便的對(duì)cout連續(xù)輸出各種內(nèi)建型別的數(shù)據(jù)或信息(也是一種objects),不必像C程序那樣需要識(shí)別不同類(lèi)型的數(shù)據(jù)在printf()中的格式符號(hào)(如?%s、%d、%f...):
1 #include <iostream.h> 2 ... 3 int i = 5; 4 double pi = 3.141592653; 5 cout << "i=" << i << " and pi=" << f << endl;
Extraction Operator(>>) for stdin:>>本來(lái)是位右移運(yùn)算符,但在C++標(biāo)準(zhǔn)的iostream中被改頭換面,其左側(cè)運(yùn)算元是cin(console input device),右側(cè)運(yùn)算元是一個(gè)內(nèi)建型別的object。例如:
1 #include <iostream.h> 2 ... 3 float f; 4 cout << "f = ? "; 5 cin >> f;
程序使用者在健盤(pán)上輸入,會(huì)經(jīng)由cin裝置流往f變量,其作用相當(dāng)于C runtime library中的scanf()。
?
Insertion Operator( <<) for file:就像iostream支持對(duì)user‘s terminal的輸入輸出一樣,c++另有一組class types支持對(duì)文件的輸入輸出:
1.ifstream衍生自istream,支持文件的輸入。
2.ofstream衍生自?ostream,支持文件的輸出。
3. fstream衍生自 iostream,?支持文件的輸入輸出。
如果需要這些class type,必須導(dǎo)入對(duì)應(yīng)的header file。請(qǐng)注意,fstream已經(jīng)含有iostream,所以不需要重復(fù)導(dǎo)入;
下面是信息輸入到文件的案例:
#0001 #include <fstream.h> // include iostream.h #0002 #0003 int main() #0004 { #0005 cout << "All your keyboard input in monitor " #0006 << "will into copy.txt.\n" #0007 << "Terminate by ^Z\n\n"; #0008 #0009 ofstream outFile("copy.txt"); #0010 if (!outFile) { #0011 cout << "Cannnot open copy.txt for output" << endl; #0012 return -1; #0013 } #0014 #0015 char c; #0016 while (cin.get(c)) // get each char from keyboard #0017 outFile << c; // outFile.put(c) 亦 可 #0018 #0019 return 0; #0020 }
當(dāng)程序執(zhí)行后,會(huì)先提示輸入,然后接收所有來(lái)自于鍵盤(pán)的字符,一一放進(jìn)”copy.txt"文件中,直到接收到^z?才停止。
Extraction Operator( >>) for file:下面是將文件的內(nèi)案輸出到屏幕上的示例:
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-858115.html
#0001 #include <fstream.h> // include iostream.h #0002 #0003 int main() #0004 { #0005 cout << "All text in copy.txt " #0006 << "will stream into monitor.\n\n"; #0007 #0008 ifstream inFile("copy.txt"); #0009 if (!inFile) { #0010 cout << "Cannnot open copy.txt for input" << endl; #0011 return -1; #0012 } #0013 #0014 char c; #0015 while (inFile.get(c)) // get each char from file #0016 cout.put(c); // output to monitor #0017 #0018 return 0; #0019 }
當(dāng)程序執(zhí)行后,會(huì)先給一個(gè)提示,然后從文件?"copy.txt"?中一一讀出每一個(gè)字符,顯示于屏幕上。上述第0015行如果改為while?(inFile >>?c)?// get each?char?from?file,雖然也能讀出字符,但空格會(huì)被忽略,這個(gè)并非我們所想要的。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-858115.html
到了這里,關(guān)于C++多態(tài)與虛擬:運(yùn)算符重載(Operator Overloading)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!