简体   繁体   中英

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.

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)

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.

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>>

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM