简体   繁体   中英

Can I overload an overloaded operator? How does Operator Overloading work

Here is the sample code:

#include <iostream>
using namespace std;

class test
{
    int a;
    int b;

    public:
    test(): a(1), b(2) {}
    ostream& operator<<(ostream&);  //FUNC 1
    friend ostream& operator<<(ostream&,test);  //FUNC 2
};

//FUNC 1
ostream& test::operator<<(ostream& obj)
{
    cout<<a<<" "<<b<<endl;
    return obj;
}

//FUNC 2
ostream& operator<<(ostream& obj, test o)
{
    cout<<o.a<<" "<<o.b<<endl;
    return obj;
}

int main()
{
    test o;
    o<<cout;      //STATEMENT 1 Calls FUNC 1
    cout<<o;      //STATEMENT 2 Calls FUNC 2 
    return 0;
}

Is there any way to use STATEMENT 2 inside the class, ie without making a friend function and passing the test object as a parameter. Using a definition like FUNC 1 for it?

Your definition of function 2 ostream& test::operator<<(ostream& obj, test o) is as a member function of the test class. You want this to be a friend function external to the class: ostream& operator<<(ostream& obj, test o) .

When you make the "output" (actually shift left) operator a member of a class, it's for making an object of the class the target of the "output".

Simple example

struct Foo
{
    Foo& operator<<(int value)
    {
        std::cout << "Output to Foo target is " << value << '\n';
        return *this;
    }
};

int main()
{
    Foo foo;
    foo << 123;
}

To use the output operator to output to another target (eg an output stream) you need to declare the operator as a non-member function:

struct Bar
{
    int value;
};

std::ostream& operator<<(std::ostream& os, const Bar& bar)
{
    os << bar.value;
}

int main()
{
    Bar bar = { 321 };
    std::cout << bar;
}

In the first example, the object ( foo ) was the target of the output operator. In the second example, the object ( bar ) is used as output to another target ( std::cout ). You can also see it like this, if you overload an operator as a member function then the object of the class (the "target" as I call it) is on the left side of the operator and the argument is on the right side of the operator.

Also, if you declare a function inside the class using friend then it's actually not a member function:

struct Fum
{
    void ho() { ... }  // ho is a member function

    friend ha() { ... }  // ha is a non-member function
};

And remember that operator functions are just normal functions, just with special names.

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