I'm still in the basic learning process of C++, and as I go though operator overloading part, I could not understand the function call steps of iostream overload operators.
My confusion is coming from the fact that C++ code below can distinguish between the fundamental-type data iostream call and class iostream call when 'the overload iostreeam functions are defined outside of my class definition via friend command.' Please take a look at below example.
#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
Now the overload function definition. #include #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;
}
Now the main function. #include #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;
}
Per my understanding, normally a function call (even operator overload functions) is obligated to follow the declaration format. So to call overload << (or >>) operator functions, the user would have to write lines like this: 'ostream a;' followed by 'cin >> ( a, phone );'. Also in above example, it appears like the line 'cin >> phone;' would be notice and directed straight to the friend function. To follow the steps per my understanding, the operator call 'cin >> phone' will first look at PhoneNumber.h declaration. However, operator declaration is not in PhoneNumber.h. It is only 'mentioned' as a friend. (My understanding of 'friend' command is that the class will SIMPLY grant a non-member function (or class) access to its private data or member functions.) Therefore, the call should confuse the compiler to call either the explicit operator function in above code, or implicit operator function in iostream.
I guess my questions are: 1. How do the operator '<<' and '>>' calls have different format than how they are declared? 2. How can the operator calls be recognized when it is not 'declared' in .h file? How does C++ know to skip .h and jump right into user defined operator functions?
Aucun commentaire:
Enregistrer un commentaire