I am trying to work on operator overloading, my header file consists of:
#ifndef PHONENUMBER_H
#define PHONENUMBER_H
#include<iostream>
#include<string>
using namespace std;
class Phonenumber
{
friend ostream &operator << ( ostream&, const Phonenumber & );
friend istream &operator >> ( istream&, Phonenumber & );
private:
string areaCode;
string exchange;
string line;
};
#endif // PHONENUMBER_H
And class definition of
//overload stream insertion and extraction operators
//for class Phonenumber
#include <iomanip>
#include "Phonenumber.h"
using namespace std;
//overloades stram insertion operator cannot be a member function
// if we would like to invoke it with
//cout<<somePhonenumber
ostream &operator << ( ostream &output, const Phonenumber &number)
{
output<<"("<<number.areaCode<<")"
<<number.exchange<<"-"<<number.line;
return output;
}//end function opertaor <<
istream &operator >> ( istream &input, Phonenumber &number)
{
input.ignore(); //skip (
input>>setw(3)>>number.areaCode;//input areacode
input.ignore(2);//skip ) and space
input>>setw(3)>>number.exchange;//input exchange
input.ignore();//skip -
input>>setw(4)>>number.line;//input line
return input;
}
calling done through main is
#include <iostream>
#include"Phonenumber.h"
using namespace std;
int main()
{
Phonenumber phone;
cout<<"Enter number in the form (123) 456-7890:"<<endl;
//cin>> phone invokes operator >> by implicitly issuing the non-member function call operator>>(cin,phone)
cin >> phone;
//cout<< phone invokes operator << by implicitly issuing the non-member function call operator>>(cout,phone)
cout << phone<<endl;
return 0;
}
but compiling this shows me a compiler error: undefined reference to 'operator>>(std:istream&, Phonenumber&)'
Could someone help me to resolve this error
istraem
in the definition of the input stream operator. But it is just a typo, isn't it? – ApologuephonenumberObj << ostrObj
? Edit: Nevermind, have somehow missed the second arguement ^^ – Brayusing namespace std;
. I wouldn't go that far, I think it's okay as long as you limit its scope. But I think everyone will agree that you shouldn't put it in the global namespace in a header. – Erythroblastusing namespace std;
in them, and you'll find out who says that. Not I. – Erythroblastusing namespace std;
fromPhonenumber.h
. – Principiumusing namespace std;
. It's not helpful for beginners; it's not helpful in large projects; it has very limited legitimate uses. stackoverflow.com/search?q=using+namespace+std+[c%2B%2B] – Noe