When I used friend for the operator functions in the PhoneNumber.h, PhoneNumber.cpp performed well. But with static it couldn't be compiled (why?) and what are the other ways to declare it (i.e) all the ways except for friend.
PhoneNumber.h
#include<iostream>
#include <string>
#include<iomanip>
using namespace std;
class PhoneNumber{
public:
string areaCode, exchange, line;
static ostream& operator<<(ostream &output, const PhoneNumber&);
static istream& operator>>(istream &input, PhoneNumber&);
};
PhoneNumber.cpp
#include"PhoneNumber.h"
using namespace std;
ostream& PhoneNumber::operator<<(ostream &output, const PhoneNumber& obj){
output << "(" <<obj. areaCode << ") "
<< obj.exchange << "-" << obj.line;
return output;
};
istream& PhoneNumber::operator>>(istream &input, PhoneNumber&obj){
input.ignore();
input >> setw( 3 ) >> obj.areaCode;
input.ignore( 2 );
input >> setw( 3 ) >> obj.exchange;
input.ignore();
input >> setw( 4 ) >> obj.line;
return input;
};
main.cpp
#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;cout << endl;
int y;cin>>y;
return 0;}
Overloaded operators cannot be static member functions, see [over.oper] (emphasis is mine).
An operator function shall either be a non-static member function or be a non-member function that has at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.