[英]C++ class iostream overloading
我仍處於C ++的基礎學習過程中,在我討論運算符重載部分時,我無法理解iostream重載運算符的函數調用步驟。
我的困惑來自這樣一個事實:當“通過Friend命令在我的類定義之外定義重載iostreeam函數”時,以下C ++代碼可以區分基本類型的數據iostream調用和類iostream調用。 請看下面的例子。
#ifndef PHONENUMBER_H
#define PHONENUMBER_H
#include <iostream>
#include <string>
class PhoneNumber
{
friend std::ostream &operator<<( std::ostream &, const PhoneNumber & )
friend std::istream &operator>>( std::istream &, PhoneNumber & )
private:
std::string areaCode;
std::string exchange;
std::string line;
};
#endif
現在,重載函數定義。
#include <iomanip>
#include "PhoneNumber.h"
using namespace std;
ostream &operator<<( ostrea &output, const PhoneNumber &number )
{
output << "(" number.areaCode << ")" << number.exchange << "-" << number.line;
return output;
}
istream &operator>>( istream &input, PhoneNumber &number )
{
input.ignore();
input >> setw( 3 ) >> number.areaCode;
input.ignore( 2 );
input >> setw( 3 ) >> number.exchange;
input.ignore();
input >> setw( 4 ) >> number.line;
return input;
}
現在的主要功能。
#include <iostream>
#include "PhoneNumber.h"
using namespace std;
int main()
{
PhoneNumber phone;
cout << "Enter phone number in the form (123) 456-7890" << endl;
cin >> phone;
cout << "The phone number entered was: ";
cout << phone << endl;
}
據我了解,通常函數調用(甚至是運算符重載函數)必須遵循聲明格式。 因此,要調用重載<<(或>>)運算符,用戶將必須編寫如下代碼:'ostream a;' 后跟“ cin >>(a,電話);”。 同樣在上面的示例中,它看起來像“ cin >> phone;”行。 將被注意並直接指向朋友功能。 按照我的理解,按照操作步驟,操作員呼叫“ cin >>電話”將首先查看PhoneNumber.h聲明。 但是,運算符聲明不在PhoneNumber.h中。 它只是被“提及”為朋友。 (我對'friend'命令的理解是,該類將簡單地授予非成員函數(或類)對其私有數據或成員函數的訪問權限。)因此,該調用應混淆編譯器以在其中調用顯式運算符函數以上代碼或iostream中的隱式運算符函數。
我想我的問題是:1.運算符“ <<”和“ >>”調用的格式與聲明的格式不同嗎? 2.在.h文件中未“聲明”時,如何識別操作員呼叫? C ++如何知道跳過.h並直接跳入用戶定義的運算符函數?
您的問題中存在一些明顯的誤解,但其余的我無法真正解析。 希望以下內容足以解決您的查詢。
這個:
cin >> x;
是語法糖(更像是您正在想象的函數調用語法):
cin.operator>>(x);
有時(在這種情況下)是這樣的:
operator>>(cin, x);
您不能為其中任何一個隨機地創造一個額外的參數!
因為它們被聲明為“運算符”功能。 與您在問題中所寫的相反,這不是“正常”功能。 正常的函數聲明為: std::ostream &<<(std::ostream &, const Phonenumber &)
(我認為不會編譯)。 但是您將其聲明為std::ostrean &operator<<(std::ostream &, const Phonenumber &)
,這使其成為運算符重載。
這似乎確實很棘手,但這是因為您在編譯器中有一個編譯步驟和一個鏈接步驟。 在編譯時,編譯器會將您的好友函數聲明解析為您在另一個文件中編寫的流運算符。 它們匹配,因為函數聲明相同,並且它們被聲明為朋友函數。 在鏈接時(這是構建最終程序的地方),如果您已告訴鏈接器組合所有這些文件,則鏈接器將嘗試查找與主循環內使用的函數匹配的對象。 如果找不到它們,您將得到類似: Undefined reference to ...
。
由於運算符調用是在頭文件中聲明的(您說不是,但實際上是聲明為朋友函數),因此編譯器和鏈接器都將成功。 編譯器不會告訴您: Use of undeclared function ...
而鏈接程序不會告訴您: Undefined reference to...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.