简体   繁体   中英

Dealing with operator overload method as a friend

I tried to create simple class and to overload some of it's operators, however, i failed at the very beginning, here's my code:

#include <iostream>

class Person
{
    char *firstName;
    char *lastName;
    int age;
    friend std::ostream &operator<<(std::ostream &, const Person &);
public:
    Person() : firstName("Piotr"),  lastName("Tchaikovsky"), age(10) {}

    Person(char* f, char* l, int a)
    {
        this->firstName = f;
        this->lastName = l;
        age = a;
    }

    std::ostream &operator<<(std::ostream& out, const Person &p)
    {
        out << p.firstName << " " << p.lastName;
        return out;
    }

};

int main()
{
    Person a;

    getchar();
    getchar();
}

So, before i created this operator overloading function i used debugger to see if constructor is going to work, and it worked, since default values were given correctly to the variable a i created, after that, all i did was that i created function that overloads the operator << and it is a friend function of my class, since i am taught that it is a good thing to do due to the type of the first parameter of overloading function, however, when i try to run this (NOTE: i have not tried to print out anything yet, i wanted to check if everything works fine first) it gives me errors saying:

"too many parameters for this operator function",

"binary 'operator <<' has too many parameters" and

" 'Person::operator<<' :error in function declaration; skipping function body"

however, i can't find any problems with function declaration, and i cannot possibly see how two parameters can be too many for this function. Any help appreciated!

You declare the friend function as a global non-member function. Then you define a member function.

Move the definition of the operator<< function to outside the class:

class Person
{
    ...
    friend std::ostream &operator<<(std::ostream &, const Person &);
    ...
};

std::ostream &operator<<(std::ostream& out, const Person &p)
{
    out << p.firstName << " " << p.lastName;
    return out;
}

Or alternatively define the friend function inline:

class Person
{
    ...
    friend std::ostream &operator<<(std::ostream &, const Person &)
    {
        out << p.firstName << " " << p.lastName;
        return out;
    }
    ...
};

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