1

I know this may sound strange, and there ways get around this.but I just wonder if it is possible in c++.

class Item{
     public:
            string name;
     Item(string input){
            name = input
            cout << this;  // unfortunately the std::ostream& operator<<(std::ostream& outstream, Item* item) are not parsed by compiler yet. and this simply prints out its address.
                cout << *this; //I don't know how to override `cout << Item`.
     }
}

std::ostream& operator<<(std::ostream& outstream, Item* item){
    outstream << item->name;
    return outstream;
}

std::ostream& operator<<(std::ostream& outstream, Item& item){
    outstream << item.name;
    return outstream;
}
0

1 Answer 1

1

Try the following

std::ostream & operator <<( std::ostream &outstream, const class Item &item );


class Item
{
     public:
            std::string name;
            Item( const std::string &input ) : name( input )
            {
                std::cout << *this;
            }
};

std::ostream & operator<<( std::ostream &outstream, const Item &item )
{
    outstream << item.name;
    return outstream;
}

Or if data member name will be defined as private then you can write

class Item
{
     private:
            std::string name;
     public:
            Item( const std::string &input ) : name( input )
            {
                std::cout << *this;
            }
           friend std::ostream & operator <<( std::ostream &outstream, const Item &item );

};

std::ostream & operator<<( std::ostream &outstream, const Item &item )
{
    outstream << item.name;
    return outstream;
}

The same way you can overload operator

std::ostream & operator <<( std::ostream &outstream, const class Item *item );

if you need. However in fact there is no need to overload this operator. It is enough to have the operator where reference to an object of thbe class is used as parameter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.