0

I have a problem with the << operator in C++. I need this operation work:

  cout << comp2 << comp1;


class Compo
{
    string name;
    int power;
    string app;

public:
    Compo(string s, string a, int p):name(s), power(p),app(a){};
    //~Compo();    

     string GetAsString()const{
        ostringstream oss;    
        oss << name << " [ " << power << " ] desc: " << app << endl;        
        return oss.str();
    };


     string &operator<<(Compo& aux)const{               
        return aux.GetAsString();
    };
};

void main()
{
    Compo comp1("Pencil","Best",12);
    Compo comp2("Notes","Not Best",22);
    cout << comp2 << comp1;        
    cin.get();
}

i have erro on cout << comp2

the error description is,

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Compo' (or there is no acceptable conversion)

and one warn alert,

returning address of local variable or temporary

ho i need change to this works.

suspectus
  • 16,548
  • 8
  • 49
  • 57
Góis
  • 27
  • 1
  • 1
  • 10

4 Answers4

1

You'll need to declare a standalone output operator method to do this (class free function).

std::ostream& operator<<(std::ostream& os, const Compo& obj)
{
    obj.put(os);
    return os;
}

In class Compo have:

// ...
public:
    void put(std::ostream& os) const
    {
        // output member values here ...
    }
// ...

UPDATE:
Or alternatively (if you can't change Comp actually):

std::ostream& operator<<(std::ostream& os, const Compo& obj)
{
    os << obj.GetAsString();
    return os;
}

IMHO the 1st solution I've proposed here is the more flexible one, for fulfilling future requirements in the end. It might be used with implementations for std::ostream that don't handle stringyfied formats.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

The compiler can't find any operator<< which takes as a left argument std::ostream and as right argument Compo. You defined one which takes as a left argument a std::string and as the right argument Compo. Try:

class Compo{
//Stuff
public:
    friend ostream& operator<<(ostream& os, Compo& aux);
};
ostream& operator<<(ostream& o, const Compo& aux)
{
    o << name << " [ " << power << " ] desc: " << app << endl;
    return o;
}
NaCl
  • 2,683
  • 2
  • 23
  • 37
0

You need something like this operator:

ostream& operator << (ostream& o, const Compo& c)
{
   return o << c.GetAsString();
}
Igor
  • 1,029
  • 9
  • 21
0
#include <iostream>

using namespace std;

class Compo
{
    string name;
    int power;
    string app;

public:
    friend ostream& operator<< (ostream&, const Compo&);
     ....
     .....

};

ostream& operator<< (ostream& out, const Compo& c)
{
   out << c.name << "[" << c.power << " ] desc: " << c.app << endl;
}