Question

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;
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top