Bob Sacamano
Bob Sacamano

Reputation: 439

failing to overload operator<< (c++)

I'm trying to overload << . No luck so far. Here's my overload implementation:

struct Engineer{
    int id;
    int salary;
    bool hired;
public:
    Engineer(int _id, int _salary) : id(_id), salary(_salary), hired(false) {}

    std::ostream& operator<<(std::ostream& os)
    {
      return os << " " << id << std::endl;
    }
};

and here's me trying to use it:

void inorderTravel(AvlNode* root) {
    if(root == NULL) return;
    inorderTravel(root->left);
    std::cout << root->data;     // <- here
    inorderTravel(root->right);
}

the line "std::cout << root->data;" evokes all the errors:

> Multiple markers at this line
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'unsigned char'
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'signed char'
>   - 'Engineer' is not derived from 'const std::basic_string<_CharT,    _Traits, _Alloc>'
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'char'
>   - deduced conflicting types for parameter '_CharT' ('char' and       'Engineer')
>   - no match for 'operator<<' (operand types are 'std::ostream {aka    std::basic_ostream<char>}' and 'Engineer')
>   - candidates are:
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'const char*'
>   - mismatched types 'const _CharT*' and 'Engineer'
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'const unsigned char*'
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'const signed char*'

Upvotes: 2

Views: 1149

Answers (2)

danielschemmel
danielschemmel

Reputation: 11116

You defined the operator std::ostream& Engineer::operator<<(std::ostream&) - so the left operand of an expression like left << right must be of type Engineer and the right operand of type std::ostream&...

You can define the right operator as a friend function in your Engineer class like so:

friend std::ostream& operator<<(std::ostream& out, Engineer const& self)
{ return out << " " << self.id << std::endl; }

Upvotes: 2

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

This is not a correct definition of operator<<. This operator should take as second argument a const reference to an instance of the class you are trying to print. Using your definition there is an implicit first argument. An operator<< can not be defined in a class, typically it is implemented as a friend function. Something like this:

struct Engineer{
  //... other code
  friend std::ostream& operator<<(std::ostream& os, const Engineer& e);
};

std::ostream& operator<<(std::ostream& os, const Engineer& e)
{
  return os << " " << id << std::endl;
}

Upvotes: 1

Related Questions