Dan Lincan
Dan Lincan

Reputation: 1065

C++ overloading >> operator strange compile error

#include <iostream>
#include <string>

using namespace std;

class phonebook
{
    string name;
    string prefix;
public:
    phonebook(string &name, string &prefix)
    {
        this->name = name;
        this->prefix = prefix;
    }

    friend istream &operator>>(istream &in, phonebook &book);
};

istream &phonebook::operator>>(istream &in, phonebook &book)
{
    in >> book.name >> book.prefix;
    return in;
}

int main()
{
    return 0;
}

When I try to compile this code using g++ 4.6.1:

"main.cpp:20: error: ‘std::istream& phonebook::operator>>(std::istream&, phonebook&)’ must take exactly one argument"

PS: It was pretty dumb thing to ask... So obvious :S. Thank you though.

Upvotes: 3

Views: 1130

Answers (5)

RoundPi
RoundPi

Reputation: 5947

because you declared friend istream &operator>>(istream &in, phonebook &book);

So this operator>> is not a member function of phonebook.

Quote from C++ 03 standard

11.4 Friends A friend of a class is a function or class that is not a member of the class but is permitted to use the private and protected member names from the class. The name of a friend is not in the scope of the class, and the friend is not called with the member access operators (5.2.5) unless it is a member of another class.

So remove the phonebook:: would work:

istream& operator>>(istream &in, phonebook &book)
{
    in >> book.name >> book.prefix;
    return in;
}

Upvotes: 1

cpx
cpx

Reputation: 17557

When you declare function a friend inside the class, you either define it inside the class or make it a non-member function.

istream & operator>>(istream &in, phonebook &book)
{
    in >> book.name >> book.prefix;
    return in;
}

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132974

You cannot overload operator >> for streaming as a member function. Any operator that is defined as a member function takes its first argument as a reference to (const) Type, where Type is your class name - in this case, phonebook.

You need to change

istream &phonebook::operator>>(istream &in, phonebook &book)

to

istream & operator>>(istream &in, phonebook &book)

Upvotes: 5

Gilad Naor
Gilad Naor

Reputation: 21516

phonebook doesn't have a method called opeartor>>

You stated that there exists a global function that is a friend of phonebook, and therefore, you should remove phonebook:: from the implementation of operator>>

Upvotes: 1

Potatoswatter
Potatoswatter

Reputation: 137770

A friend function isn't a member. As it is, it's expecting the left-hand side of the >> operator to be a phonebook. Change the first line of the function definition (outside the class) to this:

istream &operator>>(istream &in, phonebook &book)

Note there is no phonebook:: because it's not a member.

Upvotes: 3

Related Questions