overloading operator << c++, I am trying to cout the element of class

Viewed 840

I am writing this code

ostream& operator <<(ostream& out, Box& B){
    return B.l +" "+B.b +" "+B.h +endl;
};

The error I get is

Solution.cpp:40:46: error: ‘std::ostream& Box::operator<<(std::ostream&, Box&)’ must have exactly one argument ostream& operator <<(ostream& out, Box& B){ ^

can someone explain what's wrong? I dont understand.

thanks for your help :)

3 Answers

It seems you mean the following

std::ostream & operator <<( std::ostream& out, const Box& B) {
    return out << B.l << " " << B.b << " " << B.h;
}

provided that all used in the operator data members are public data members of the class Box. The operator shall be declared and defined outside the class definition.

If one of the used data members is a private data member of the class then the function should be a friend function of the class and shall be declared (and may be defined) in the class definition. For example

class Box
{
    //...
    friend std::ostream & operator <<( std::ostream& out, const Box& B) {
        return out << B.l << " " << B.b << " " << B.h;
    }
    //...
};

Pay attention to that it is better to remove in the return statement the operand std::endl. In this case 1) the operator will be more flexible because you can output additional information in the same line and 2) this statement

std::cout << box;

will not confuse readers of the code because they will not see the operand std::endl.

Without this operand in the operator definition in the caller of the operator you can write

std::cout << box << std::endl;

and this statement more clear expresses the intention of the programmer.

It should probably be:

std::ostream& operator<<(std::ostream& out, Box const& B){
    out << B.l << " " << B.b << " " << B.h << std::endl;
    return out;
};

Full code should look like:

#include <iostream>

class Box {
    int l;
    int b;
    int h;

    friend std::ostream& operator<<(std::ostream& out, Box const& B);
};

std::ostream& operator<<(std::ostream& out, Box const& B){
    out << B.l << " " << B.b << " " << B.h << std::endl;
    return out;
}

int main() {
    return 0;
}

Demo

To output a type T to std::ostream, you have to declare standalone operator, which returns reference to that stream

std::ostream& operator<<(std::ostream& out, const T& B)
{
    out << B.l << " " << B.b << " " << B.h << '\n';
    return out;
}

This operation cannot be member operator because member operator use their class as first argument, therefore it might be necessary declare it as a friend of class T.

Avoid using endl in such operators if not extremely necessary, that manipulator calls out.flush(). If you want new line added, use new-line character.

Related