简体   繁体   中英

Overload left shift operator << to object

I am not able to overload the left shift operator "<<" so I can use the following code:

Foo bar;
bar << 1 << 2 << 3;

My class Foo looks like this:

class Foo{
private:
    vector<int> list;
public:
    Foo();
    void operator<<(int input);
};

And the implementation like this:

void Foo::operator<<(int input)
{
   // here i want to add the different int values to the vector 
   // the implementation is not the problem
}

The code doesn't work I get an error "left operand is of type 'void' ". When I change the return type to Foo& it tells me to return something of the type Foo . The problem is I can't. I am missing a object reference of the object bar .

I searched alot but only found pages who described the operator to output to cout.

To enable chaining you must return a reference from the operator. When you write

bar << 1 << 2 << 3;

That actually is

((bar << 1) << 2) << 3;

ie operator<< is called on the result of bar << 1 with parameter 2 .

The problem is I can't. I am missing a object reference of the object bar.

You seem to miss that your operator<< is a member function. In bar s member functions *this is a reference to the bar object:

#include <vector> 
#include <iostream>

class Foo{
private:
    std::vector<int> list;
public:
    Foo() {}
    Foo& operator<<(int input);
    void print() const { for (const auto& e : list) std::cout << e << ' ';}
};

Foo& Foo::operator<<(int input)
{
    list.push_back(input);
    return *this;
}

int main() {
    Foo bar;
    bar << 1 << 2 << 3;
    bar.print();
}

PS: While constructs such as bar << 1 << 2 << 3; can be found in several libraries that predate C++11, nowadays it looks a little old fashioned. You would rather use list initialization or provide a std::initializer_list<int> constructor to enable Foo bar{1,2,3}; .

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